About
A nodelist is the result of a selection that returns more than one node (Generally an element)
Nodelist:
- HTMLAllCollection,
- HTMLFormControlsCollection,
- HTMLOptionsCollection,
- interfaces are collections derived from the HTMLCollection interface.
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
- With pure Javascript, selectAll
document.querySelectorAll('Selector').length
- With JQuery
jQuery(selector).length
toArray
You can transform it to an array:
- With the spread operator,
let arrayOfNode = [...document.querySelectorAll("selector")];
- With the Array.from
let arrayOfNode = Array.from(document.querySelectorAll("selector"));
- With the slice function
let arrayOfNode = [].slice.call(document.querySelectorAll('selector'));
Loop
- A list of div element where we want to 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");
- A for Loop
for (i = 0; i < allDivs.length; i++) {
console.log("Li element number "+i+" - "+allDivs[i].textContent);
}
ForEach
- A nodelist has also a forEach
- A HTML collection can be turned as an array Array.from()
let sentence ="";
document.querySelectorAll("#my-list > li").forEach(element => {
let text = element.innerText;
if (text == "can" ) {
text = "can not";
}
sentence += text+" ";
})
console.log(sentence);
- Result
For more see DOM - Collection Iteration (NodeList, ..)