Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through childNodes

I'm trying to loop through childNodes like this:

var children = element.childNodes; children.forEach(function(item){     console.log(item); }); 

However, it output Uncaught TypeError: undefined is not a function due to forEach function. I also try to use children instead of childNodes but nothing changed.

Does anybody know what's going on?

like image 944
user3828771 Avatar asked Jul 16 '14 08:07

user3828771


People also ask

What does childNodes mean?

The childNodes property is a property of Node in Javascript and is used to return a Nodelist of child nodes. Nodelist items are objects, not strings and they can be accessed using index numbers. The first childNode starts at index 0. Syntax element.childNodes.

How do you iterate a child?

To iterate over Children of HTML Element in JavaScript, get the reference to this HTML Element, get children of this HTML using using children property, then use for loop to iterate over the children.

What does childNodes return?

childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.


2 Answers

The variable children is a NodeList instance and NodeLists 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.

like image 178
GillesC Avatar answered Oct 05 '22 17:10

GillesC


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); } 
like image 24
Emmet Avatar answered Oct 05 '22 16:10

Emmet