Table of Contents

DOM - NodeList (Collection)

About

A nodelist is the result of a selection that returns more than one node (Generally an element)

Nodelist:

Management

Type and prototype

let nodeList = document.querySelectorAll("body")
console.log("Type of NodeList: "+typeof(nodeList));
console.log("Prototype of NodeList: "+nodeList.__proto__.toString());

Length

document.querySelectorAll('Selector').length
jQuery(selector).length

toArray

You can transform it to an array:

let arrayOfNode = [...document.querySelectorAll("selector")];
let arrayOfNode = Array.from(document.querySelectorAll("selector"));
let arrayOfNode = [].slice.call(document.querySelectorAll('selector'));

Loop

<ul id="my-list">
    <li>You</li>
    <li>can</li>
    <li>do</li>
    <li>JS</li>
</ul>

Property loop

Because a nodelist is just an object, we can loop through its properties with the for statement

// Get all divs element
// allDivs is an array of NodeList
allDivs=document.querySelectorAll("#my-list > li");
for (i = 0; i < allDivs.length; i++) {
    console.log("Li element number "+i+" - "+allDivs[i].textContent);
}

ForEach

let sentence ="";
document.querySelectorAll("#my-list > li").forEach(element => {
  let text = element.innerText;
  if (text == "can" ) {
     text = "can not";
  }
  sentence += text+" ";
})
console.log(sentence);

For more see DOM - Collection Iteration (NodeList, ..)

Documentation / Reference