Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this loop all children recursively?

I have the following:

for (var i = 0; i < children.length; i++){    if(hasClass(children[i], "lbExclude")){        children[i].parentNode.removeChild(children[i]);    } }; 

I would like it to loop through all children's children, etc (not just the top level). I found this line, which seems to do that:

for(var m = n.firstChild; m != null; m = m.nextSibling) { 

But I'm unclear on how I refer to the current child if I make that switch? I would no longer have i to clarify the index position of the child. Any suggestions?

Thanks!

Update:

I'm now using the following, according to answer suggestions. Is this the correct / most efficient way of doing so?

function removeTest(child) {   if (hasClass(child, "lbExclude")) {     child.parentNode.removeChild(child);   } }  function allDescendants(node) {   for (var i = 0; i < node.childNodes.length; i++) {     var child = node.childNodes[i];     allDescendants(child);     removeTest(child);   } }  var children = temp.childNodes; for (var i = 0; i < children.length; i++) {   allDescendants(children[i]); }; 
like image 468
Matrym Avatar asked Apr 26 '10 08:04

Matrym


People also ask

How do you stop a recursive loop?

Use a return; statement where the code needs to stop and go back to its predecessor (which will in turn also call the return; , and so on...)

How do you get all the children of a node?

To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node's child nodes, as a NodeList object. By default, the nodes in the collection are sorted by their appearance in the source code. You can use a numerical index (start from 0) to access individual nodes.


2 Answers

function allDescendants (node) {     for (var i = 0; i < node.childNodes.length; i++) {       var child = node.childNodes[i];       allDescendants(child);       doSomethingToNode(child);     } } 

You loop over all the children, and for each element, you call the same function and have it loop over the children of that element.

like image 63
Quentin Avatar answered Sep 30 '22 09:09

Quentin


Normally you'd have a function that could be called recursively on all nodes. It really depends on what you want to do to the children. If you simply want to gather all descendants, then element.getElementsByTagName may be a better option.

var all = node.getElementsByTagName('*');  for (var i = -1, l = all.length; ++i < l;) {     removeTest(all[i]); } 
like image 26
James Avatar answered Sep 30 '22 07:09

James