Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Loop Through every third child node

Tags:

javascript

dom

If I got a parent node, how can I loop through every third child node?

I've got now this code:

var parents = document.getElementById('ID_of_parent');
var first_child = parents.firstChild.data.id;
alert(parents);
alert(first_child);

For the parents, i got now '[object HTMLDivElement]' and for first_child i got 'undefined'.

like image 246
Florian Müller Avatar asked Nov 25 '10 07:11

Florian Müller


2 Answers

var nodes = document.getElementById('ID_of_parent').childNodes;
for(i=0; i<nodes.length; i+=3) {
    alert(nodes[i]);
}
like image 82
Gabi Purcaru Avatar answered Sep 20 '22 17:09

Gabi Purcaru


Have you consider jQuery?

$("#ID_of_parent > *:nth-child(3n)").each(function() { alert(this);});

I implemented a demo here: http://jsbin.com/ahije4/5

like image 32
Tomas Jansson Avatar answered Sep 19 '22 17:09

Tomas Jansson