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");

Comments

  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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Using Trello and Confluence to manage UX design project. Part 2

How do I use InVision

Using Trello and Confluence to manage UX design project. Part 1