121

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?

user3828771
  • 1,603
  • 3
  • 14
  • 14

11 Answers11

164

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.

GillesC
  • 10,647
  • 3
  • 40
  • 55
  • How could I convert NodeList to pure array? – user3828771 Jul 16 '14 at 08:27
  • Updated with example but read the link I posted it explains it all :) – GillesC Jul 16 '14 at 08:28
  • 2
    Alternatively, you can do this: `[].forEach.call(element.childNodes, child => console.log(child))` – XåpplI'-I0llwlg'I - Jun 03 '15 at 13:33
  • 2
    Even cooler es6 way: `let items = [ ...children ]` will turn it into an array – zackify Jul 11 '16 at 00:36
  • 4
    There is a major gotcha with applying Array methods to NodeLists: NodeLists such as node.childNodes are live lists, and if you manipulate the DOM during your loop the NodeList is subject to change, meaning the callback to forEach() my not get called on every element of the list - or more elements than were originally in the list - leading to unpredictable results. It is preferable to turn a NodeList into an array before looping over it. – stephband Dec 15 '16 at 13:57
  • Also works: for (let i=0; i < obj.childNodes.length; i++) { const childNode = obj.childNodes[i]; } – Adam Rosenthal Jun 16 '20 at 13:22
40

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);
}
Emmet
  • 6,192
  • 26
  • 39
30

Here is how you can do it with for-in loop.

var children = element.childNodes;

for(var child in children){
    console.log(children[child]);
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
AdityaParab
  • 7,024
  • 3
  • 27
  • 40
7
const results = Array.from(myNodeList.values()).map(parser_item);

NodeList is not Array but NodeList.values() return a Array Iterator, so can convert it to Array.

Xu Qinghan
  • 153
  • 1
  • 6
5

Couldn't resist to add another method, using childElementCount. It returns the number of child element nodes from a given parent, so you can loop over it.

for(var i=0, len = parent.childElementCount ; i < len; ++i){
    ... do something with parent.children[i]
    }
Michel
  • 4,076
  • 4
  • 34
  • 52
  • 1
    Beware, `parent.childElementCount != parent.childNodes.length`. `childElementCount` returns the number of `Element` nodes and does not include text and comment nodes, etc. See: https://www.w3schools.com/jsref/prop_element_childelementcount.asp – Mark Feb 17 '21 at 09:56
  • @Mark As it says in the answer: _"returns the number of child_ **element** _nodes_". But it's good emphasizing it. – Michel Feb 17 '21 at 10:08
  • No worries. Technically your answer is correct, it is talking about *element* count and *children*, but I just wanted to add the heads-up, since the initial question was about *nodes*. Too many ways to shoot yourself in the foot :) – Mark Feb 17 '21 at 12:51
4

Try with for loop. It gives error in forEach because it is a collection of nodes nodelist.

Or this should convert node-list to array

function toArray(obj) {
  var array = [];
  for (var i = 0; i < obj.length; i++) { 
    array[i] = obj[i];
  }
return array;
}

Or you can use this

var array = Array.prototype.slice.call(obj);
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
4

Here is a functional ES6 way of iterating over a NodeList. This method uses the Array's forEach like so:

Array.prototype.forEach.call(element.childNodes, f)

Where f is the iterator function that receives a child nodes as it's first parameter and the index as the second.

If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:

const forEach = f => x => Array.prototype.forEach.call(x, f);

// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)

// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)

(You can do the same trick for map() and other Array functions.)

F Lekschas
  • 12,481
  • 10
  • 60
  • 72
3

Try this [reverse order traversal]:

var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
    console.log('node: ', childs[len]);
} while(len --);

OR [in order traversal]

var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
    console.log('node: ', childs[i]);
} while(++i < len);
0

If you do a lot of this sort of thing then it might be worth defining the function for yourself.

if (typeof NodeList.prototype.forEach == "undefined"){
    NodeList.prototype.forEach = function (cb){
        for (var i=0; i < this.length; i++) {
            var node = this[i];
            cb( node, i );
        }
    };
}
CarbonMan
  • 4,350
  • 12
  • 54
  • 75
0
for (var i = 0; i < e.childNodes.length; i++) {
        var id = e.childNodes[i].id;
    }
Muisca
  • 69
  • 1
  • 5
  • 1
    There's no need to use `var` anymore, and `for...of` is much cleaner, I think. – General Grievance Dec 01 '22 at 14:04
  • for...of is much cleaner ??? And red is the most beautiful color... The question is: Loop through childNodes. And my for loop does it very effectively, very C-style.. – Muisca Dec 02 '22 at 18:48
  • 1
    I'm not saying it doesn't work. I'm just saying that this style of looping over iterable objects and the usage of `var` for variable declaration in JS is a little dated. Does writing it C-style offer a big advantage? – General Grievance Dec 02 '22 at 20:06
-1

Just Change children to [...children] to convert NodeList to the array of Nodes, so .forEach can be worked.

let element = document.querySelector('ul');
var children = element.childNodes;
[...children].forEach(function(item){
    console.log(item);
});
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
Jordy
  • 1,802
  • 2
  • 6
  • 25