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]); };
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...)
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.
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.
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]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With