San Francisco Bay Area Professional Blog: Traverse/walk DOM tree recursively
Traverse/walk DOM tree recursively
Task definition: You have a DOM tree (startNode which can be the whole document), and need to find first specific tag in this tree.
Here is the recursion function to do this:1.
function
findNodeByTag(startNode, tagName) {
2.
if
(startNode.nodeName.toLowerCase() == tagName.toLowerCase())
return
startNode;
3.
var
childList = startNode.childNodes;
4.
for
(
var
i=0; i<childList.length; i++) {
5.
return
findNodeByTag(childList[i], tagName);
6.
}
7.
return
null
;
8.
}
And you call it:1.
findNodeByTag(myDOMobj,
"img"
);