Sometimes, we want to loop through children objects in JavaScript.
In this article, we’ll look at how to loop through children objects in JavaScript.
How to loop through children objects in JavaScript?
To loop through children objects in JavaScript, we can use the spread operator and the forEach
method.
For instance, we write
const listItems = document.querySelector("ul").children;
const listArray = [...listItems];
listArray.forEach((item) => {
console.log(item);
});
to select all children from the ul
with querySelector
and children
.
And then we convert the listItem
node list to an array with the spread operator.
Then we call listArray.forEach
with a callback to loop through each entry.
Conclusion
To loop through children objects in JavaScript, we can use the spread operator and the forEach
method.