JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Node Lists


What is a NodeList?

A NodeList in JavaScript is a collection of nodes returned by methods like querySelectorAll or childNodes. Unlike an individual DOM element, a NodeList allows you to access multiple nodes at once.

NodeLists can be static or live, and they are often used for iterating over multiple elements to apply changes dynamically.

NodeList vs HTMLCollection

Feature NodeList HTMLCollection
Node Types Elements, text, comment nodes Elements only
Live or Static Can be static or live Always live
Looping forEach, for, for…of for or convert to array
Creation querySelectorAll, childNodes getElementsByTagName, children
  • NodeList is more versatile because it can contain any node type.

  • HTMLCollection is limited to element nodes.

Accessing Nodes in a NodeList

let nodeList = document.querySelectorAll("p"); // Static NodeList
console.log(nodeList); // Logs all <p> elements

// Access the first paragraph
console.log(nodeList[0]);

// Access the last paragraph
console.log(nodeList[nodeList.length - 1]);
  • NodeLists are array-like, meaning you can use indexing but not all array methods without conversion.

Static vs Live NodeLists

Static NodeList

Returned by methods like querySelectorAll, does not update automatically when the DOM changes.

let paragraphs = document.querySelectorAll("p");
let newP = document.createElement("p");
newP.textContent = "New Paragraph";
document.body.appendChild(newP);

console.log(paragraphs.length); // Original count, does not include newP

Live NodeList

Returned by properties like childNodes, updates automatically when the DOM changes.

let childNodes = document.body.childNodes;
let newDiv = document.createElement("div");
document.body.appendChild(newDiv);

console.log(childNodes.length); // Includes newDiv automatically

Looping Through a NodeList

Using for loop

let paragraphs = document.querySelectorAll("p");

for (let i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.color = "blue"; // Change text color
}

Using for…of loop

for (let para of paragraphs) {
    para.style.backgroundColor = "#f0f0f0"; // Change background
}

Using forEach (for NodeList only)

paragraphs.forEach((para, index) => {
    para.textContent = `Paragraph ${index + 1}`; // Update text
});

Unlike HTMLCollections, NodeLists support forEach directly, which makes iteration convenient.

Converting NodeList to Array

Sometimes you need full array functionality, like map, filter, or reduce.

let nodeList = document.querySelectorAll("li");
let nodeArray = Array.from(nodeList);

nodeArray.map(li => {
    li.style.fontWeight = "bold";
});
  • Array.from() converts the NodeList into a real array.

  • Useful when performing advanced array operations on multiple elements.

Accessing Node Properties

Each node in a NodeList has standard node properties:

let nodeList = document.querySelectorAll("p");

nodeList.forEach(node => {
    console.log("Node Name:", node.nodeName); // e.g., P
    console.log("Node Type:", node.nodeType); // 1 = element node
    console.log("Parent Node:", node.parentNode); // Parent element
});
  • nodeName – Returns the tag name or #text for text nodes.

  • nodeType – Returns numeric code indicating type.

  • parentNode – Returns the parent element.

Practical Example: Styling Multiple Elements

<ul class="menu">
    <li>Home</li>
    <li>About</li>
    <li>Services</li>
    <li>Contact</li>
</ul>
let menuItems = document.querySelectorAll(".menu li"); // NodeList

menuItems.forEach((item, index) => {
    item.style.padding = "10px";
    item.style.cursor = "pointer";

    // Highlight every second item
    if (index % 2 !== 0) {
        item.style.backgroundColor = "#e0e0e0";
    }
});
  • NodeList allows batch processing of multiple elements.

  • Easy to apply styles, classes, or content updates.

Adding and Removing Nodes with NodeLists

NodeLists are often read-only, meaning you cannot directly modify the list. Instead, modify the DOM elements themselves:

let nodeList = document.querySelectorAll("p");

// Add a new paragraph
let newPara = document.createElement("p");
newPara.textContent = "I am new!";
document.body.appendChild(newPara);

// The NodeList does not include newPara (static NodeList)
console.log(nodeList.length); // Original count
  • Use live NodeLists (childNodes) if you need automatic updates.

Best Practices

  • Use querySelectorAll for static NodeLists for predictable behavior.

  • Convert NodeLists to arrays when using array methods.

  • Use forEach or for…of for clean iteration.

  • Understand whether your NodeList is static or live to avoid unexpected bugs.

  • Use NodeLists for batch operations on multiple elements for performance and cleaner code.

Summary of the Tutorial

DOM NodeLists are collections of nodes that allow you to access and manipulate multiple elements. Key points:

  • Can contain element, text, and comment nodes.

  • Can be static (querySelectorAll) or live (childNodes).

  • Supports looping with for, for…of, or forEach.

  • Can be converted to arrays for advanced operations.

  • Essential for dynamic, interactive web applications that manipulate multiple elements efficiently.

Mastering NodeLists enables you to work with multiple DOM elements at once, apply batch updates, and write cleaner, more efficient JavaScript.


Practice Questions

  1. How can you select all <p> elements on a page using querySelectorAll and change their text color to red?

  2. Write a loop to iterate through all <li> items in a menu using forEach and add 10px padding to each.

  3. How can you convert a NodeList of all <div> elements into an array and change their background color?

  4. How would you select all headings (h1 and h2) and append (Updated) to their text content?

  5. How can you access the first and last nodes in a NodeList and make their font weight bold?

  6. Write code to loop through all buttons in a NodeList and attach a click event that logs their text content.

  7. How can you select all elements with the class .item and toggle a CSS class on each using a for…of loop?

  8. Using childNodes, how would you loop through all child nodes of a container and log their node types?

  9. How can you select all <input> elements in a form using a NodeList and reset their values to empty?

  10. If you create a new <p> element and append it to the body, will it appear in a static NodeList obtained earlier using querySelectorAll("p")? Explain why.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top