JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



DOM Node Lists

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can interact with the page.

A DOM node list is an array-like collection of nodes. It is returned by many DOM methods, such as getElementsByTagName(), getElementsByClassName(), and querySelectorAll(). A node list is not an array, but it can be converted into one using the Array.from() method.

Node lists are live collections, which means that they are updated automatically when the document changes. For example, if you add a new element to the document, it will be added to the node list returned by getElementsByTagName().

Here is an example of how to use a node list:

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  const listItems = document.getElementById("myList").getElementsByTagName("li");
  for (let i = 0; i < listItems.length; i++) {
    console.log(listItems[i].textContent);
  }
</script>

In this example, we get all the <li> elements inside the <ul> element with the ID "myList". We then loop through the node list and log the text content of each <li> element to the console.

Node lists have a length property, which tells you how many nodes are in the list. They also have methods for accessing nodes by index, such as item() and bracket notation ([]). For example:

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  const listItems = document.getElementById("myList").getElementsByTagName("li");
  console.log(listItems.length); // 3
  console.log(listItems.item(1).textContent); // "Item 2"
  console.log(listItems[2].textContent); // "Item 3"
</script>

Node lists are useful for performing operations on multiple nodes at once. For example, you can use a node list to add a class to all elements that match a certain selector:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  const listItems = document.querySelectorAll("li");
  listItems.forEach(item => {
    item.classList.add("highlight");
  });
</script>

In this example, we use querySelectorAll() to get all the <li> elements on the page. We then use the forEach() method to loop through the node list and add the "highlight" class to each element.

Node lists are a powerful tool for working with the DOM. They allow you to access and manipulate multiple nodes at once, making it easier to create dynamic and interactive web pages.

References

Activity