Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript HTML DOM Node List

JavaScript HTML DOM Node List

NodeList The object is a NodeList (collection) retrieved from the document.

The NodeList object is similar to HTMLCollection object.

Methods in some older browsers (such asgetElementsByClassName()) return a NodeList object instead of an HTMLCollection object.

All browsers' childNodes property returns a NodeList object.

Most browsers' querySelectorAll() return a NodeList object.

The following code selects all the elements in the document

nodes in the document:

Example

var

myNodeList

=

document

.

querySelectorAll

(

"

p

"

)

;

Elements in a NodeList can be accessed by index (starting at 0).

Access the second

element with the following code:

y = myNodeList[1];

Try it »


NodeList Object length Property

The length property of a NodeList object defines the number of elements in the node list.

Example

var

myNodelist

=

document

.

querySelectorAll

(

"

p

"

)

;

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

myNodelist

.

length

;

Try it »

Example Parsing

Obtain the

A collection of elements:

var myNodelist = document.querySelectorAll("p");

Display the number of elements in the node list:

document.getElementById("demo").innerHTML = myNodelist.length;

The length property is often used to iterate over a node list.

Example

Modify all the elements in the node list

elements' background color:

var

myNodelist

=

document

.

querySelectorAll

(

"

p

"

)

;

var

i

;

for

(

i

=

0

;

i

<

myNodelist

.

length

;

i

++

)

{

myNodelist

[

i

]

.

style

.

backgroundColor

=

"

red

"

;

}

Try it »


The Difference Between HTMLCollection and NodeList

HTMLCollection is a collection of HTML elements.

A NodeList is a collection of document nodes.

NodeList and HTMLCollection have a lot in common.

Both NodeList and HTMLCollection are somewhat similar to array objects; elements can be accessed using indexes (0, 1, 2, 3, 4, ...).

Both NodeList and HTMLCollection have a length property.

HTMLCollection elements can be accessed by name, id, or index.

NodeList elements can only be accessed by index.

Only NodeList objects can contain attribute nodes and text nodes.

A NodeList is not an array!


A NodeList may look like an array, but it is not.

You can use indexes to get elements just like with an array.

A NodeList cannot use array methods such as valueOf(), pop(), push(), or join().