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:
function findNodeByTag(startNode, tagName) {
    if (startNode.nodeName.toLowerCase() == tagName.toLowerCase()) return startNode;
    var childList = startNode.childNodes;
    for (var i=0; i<childList.length; i++) {
        return findNodeByTag(childList[i], tagName);
    return null;

And you call it:
findNodeByTag(myDOMobj, "img");


  1. I would think that you needn't return anything. You are just calling the function. You don't want to get out of it. Once you return you will be done.


Post a Comment

Popular posts from this blog

Data visualization for Roadmap Microsite (Angular and D3.js)

Conceptual design

Four tools for prototyping: Sketch, Figma, Principle, and FramerX