Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created October 7, 2013 09:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umidjons/6865350 to your computer and use it in GitHub Desktop.
Save umidjons/6865350 to your computer and use it in GitHub Desktop.
Traverse DOM elements recursively.
var walkDom=function(html_elem, func)
{
if(typeof func!='function') return;
var loop=function(html_elem)
{
do
{
func(html_elem); // call callback for every element
if(html_elem.hasChildNodes())
loop(html_elem.firstChild);
}while(html_elem=html_elem.nextSibling);
};
loop(html_elem);
//loop(html_elem.firstChild); // do not include siblings of start element
}
var fn=function(html_elem)
{
console.log('Elem:', html_elem);
}
walkDom(document.body, fn);
function walkDom(start_element)
{
var arr=[]; // we can gather elements here
var loop=function(element)
{
do{
// we can do something with element
if(element.nodeType==1) // do not include text nodes
arr.push(element);
if(element.hasChildNodes())
loop(element.firstChild);
}
while(element=element.nextSibling);
}
loop(start_element);
//loop(start_elem.firstChild); // do not include siblings of start element
return arr;
}
walkDom(document.body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment