In JavaScript, you can iterate through a NodeList (a collection of nodes returned by methods like querySelectorAll
, getElementsByClassName
, getElementsByTagName
, etc.) using several methods. Here are a few common ones:
for
loop:var nodes = document.querySelectorAll('.your-class');
// Using a for loop
for (var i = 0; i < nodes.length; i++) {
console.log(nodes[i]);
}
forEach
method:Please note that NodeList.forEach
is not supported in older browsers (IE, Edge < 18). If you need to support older browsers, you should use a regular for
loop or Array's forEach
method with Array.from()
or [...spread]
operator.
var nodes = document.querySelectorAll('.your-class');
// Using forEach
nodes.forEach(function(node) {
console.log(node);
});
for...of
loop:for...of
loop is also not supported in older browsers (IE, Edge < 15).
var nodes = document.querySelectorAll('.your-class');
// Using for...of
for (let node of nodes) {
console.log(node);
}
You can use Array.from()
or [...spread]
operator to convert NodeList to an array and then use any of the array methods.
var nodes = document.querySelectorAll('.your-class');
// Using Array.from()
Array.from(nodes).forEach(function(node) {
console.log(node);
});
var nodes = document.querySelectorAll('.your-class');
// Using spread operator
[...nodes].forEach(function(node) {
console.log(node);
});