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);
});
This chatbot (Alphonsio) provides automated responses generated by machine-learning algorithms and relies on the accuracy of the underlying language models. While this Chatbot is programmed to provide accurate and relevant information, its information may not always be exhaustive, accurate, up-to-date or tailored to individual circumstances. It is not a substitute for professional advice or consultation with qualified experts. This chatbots and its responses are intended for informational purposes only and should not be used for commercial or business purposes. The creators of this chatbot are not liable for any damages or losses incurred as a result of using the information provided. By using our website, you acknowledge and agree to these terms. The data you submit to this chatbot is used to improve our algorithms. Under no circumstances should you submit sensitive data such as, but not limited to, personal data or passwords. The data you submit could then be made public.