Loop through childNodes
Here is how you can do it with for-in
loop.
var children = element.childNodes;
for(child in children){
console.log(children[child]);
}
I'm very late to the party, but since element.lastChild.nextSibling === null
, the following seems like the most straightforward option to me:
for(var child=element.firstChild; child!==null; child=child.nextSibling) {
console.log(child);
}
The variable children
is a NodeList
instance and NodeList
s are not true Array
and therefore they do not inherit the forEach
method.
Also some browsers actually support it nodeList.forEach
ES5
You can use slice
from Array
to convert the NodeList
into a proper Array
.
var array = Array.prototype.slice.call(children);
You could also simply use call
to invoke forEach
and pass it the NodeList
as context.
[].forEach.call(children, function(child) {});
ES6
You can use the from
method to convert your NodeList
into an Array
.
var array = Array.from(children);
Or you can also use the spread syntax ...
like so
let array = [ ...children ];
A hack that can be used is NodeList.prototype.forEach = Array.prototype.forEach
and you can then use forEach
with any NodeList
without having to convert them each time.
NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
See A comprehensive dive into NodeLists, Arrays, converting NodeLists and understanding the DOM for a good explanation and other ways to do it.