Skip to content

Instantly share code, notes, and snippets.

@fiveminuteargument
Last active February 24, 2016 08:27
Show Gist options
  • Save fiveminuteargument/2367379 to your computer and use it in GitHub Desktop.
Save fiveminuteargument/2367379 to your computer and use it in GitHub Desktop.
Iterative approach to walking a DOM tree in javascript
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);
}
@fiveminuteargument
Copy link
Author

Moving from one DOM node to the next is easy - you don't need recursion!

  1. Move to your firstChild, if you have one
  2. If not, move to your nextSibling, if you have one
  3. Failing that, back up the tree, trying to move to the nextSibling of your closest ancestor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment