How to recursively search all parentNodes

前端 未结 5 606
耶瑟儿~
耶瑟儿~ 2020-12-14 02:16

I want to know, how to find out recursively all parent nodes of an element. Suppose i have following snippet

Hello

5条回答
  •  忘掉有多难
    2020-12-14 02:45

    You can traverse from an element up to the root looking for the desired tag:

    function findUpTag(el, tag) {
        while (el.parentNode) {
            el = el.parentNode;
            if (el.tagName === tag)
                return el;
        }
        return null;
    }
    

    You call this method with your start element:

    var el = document.getElementById("...");  // start element
    var a = findUpTag(el, "A");   // search 
    if (a) console.log(a.id);
    

提交回复
热议问题