Last active
February 24, 2016 08:27
-
-
Save fiveminuteargument/2367379 to your computer and use it in GitHub Desktop.
Iterative approach to walking a DOM tree in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function visit_nodes_iterative(node) { | |
node = node || document; | |
do | |
{ | |
/* Do something with node here */ | |
node = node.firstChild || node.nextSibling || function() { | |
while ((node = node.parentNode) && !node.nextSibling); | |
return node ? node.nextSibling : null; | |
}(); | |
} | |
while (node); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Moving from one DOM node to the next is easy - you don't need recursion!
firstChild
, if you have onenextSibling
, if you have onenextSibling
of your closest ancestor