Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

HTML DOM Node List Length

The length property specifies the number of nodes in a NodeList.

Example

myNodelist.length

The length property is useful for iterating through the nodes in a NodeList.

Example

Modify the color of all <p> elements in a NodeList:

const myNodelist = document.querySelectorAll(“p”);
for (let i = 0; i < myNodelist.length; i++) {
  myNodelist[i].style.color = “red”;
}

The Difference Between an HTMLCollection and a NodeList

NodeList and an HTMLCollection are quite similar:

  • Both are array-like collections (lists) of nodes (elements) extracted from a document, and nodes can be accessed by their index number, starting at 0.
  • Both have a length property that returns the number of items in the collection.
  • An HTMLCollection contains only document elements.
  • A NodeList includes various document nodes, such as element nodes, attribute nodes, and text nodes.
  • HTMLCollection items can be accessed by name, id, or index number.
  • NodeList items can only be accessed by their index number.

Key differences:

  • An HTMLCollection is a live collection. For example, if a <li> element is added to a list in the DOM, the HTMLCollection will automatically update.
  • A NodeList is usually static. For instance, adding a <li> element to a list will not change the NodeList.
  • The getElementsByClassName() and getElementsByTagName() methods return live HTMLCollections.
  • The querySelectorAll() method returns a static NodeList.
  • The childNodes property returns a live NodeList.

Not an Array!

A NodeList may appear similar to an array, but it is not an array.

You can iterate over a NodeList and access its nodes by index.

However, you cannot use array methods like push(), pop(), or join() on a NodeList.