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.functionfindNodeByTag(startNode, tagName) {2.if(startNode.nodeName.toLowerCase() == tagName.toLowerCase())returnstartNode;3.varchildList = startNode.childNodes;4.for(vari=0; i<childList.length; i++) {5.returnfindNodeByTag(childList[i], tagName);6.}7.returnnull;8.}
And you call it:1.findNodeByTag(myDOMobj,"img");
浙公网安备 33010602011771号