How do I make this loop all children recursively?

Matrym picture Matrym · Apr 26, 2010 · Viewed 49.5k times · Source

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]);
};

Answer

Quentin picture Quentin · Apr 26, 2010
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.