Created
October 7, 2013 09:54
-
-
Save umidjons/6865350 to your computer and use it in GitHub Desktop.
Traverse DOM elements recursively.
This file contains 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
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); |
This file contains 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 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