How to recursively search all parentNodes

前端 未结 5 596
耶瑟儿~
耶瑟儿~ 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:42

    Here's a shorter one:

    function parentByTag(el, tag) {
        if(!el || el.tagName == tag) {
            return el
        } else {
            return parentByTag(el.parentElement, tag)
        }
    }
    

    Returns undefined if not found.

    0 讨论(0)
  • 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 <a ...>
    if (a) console.log(a.id);
    
    0 讨论(0)
  • 2020-12-14 02:50

    The following recursive function will return an ascending ordered array, with all the parents nodes for the provided DOM element, until BODY node is reached.

    function parents(element, _array) {
        if(_array === undefined) _array = []; // initial call
        else _array.push(element); // add current element
        // do recursion until BODY is reached
        if(element.tagName !== 'BODY' ) return parents(element.parentNode, _array);
        else return _array;
    }
    

    Usage :

    var parentsArray = parents( document.getElementById("myDiv") );
    
    0 讨论(0)
  • 2020-12-14 02:51

    I been working on similar thing. Trying to close a div if user clicks outside the div. It needs to loop through all its parent nodes.

    have a look at this: http://jsfiddle.net/aamir/y7mEY/

    0 讨论(0)
  • 2020-12-14 02:56

    You can use jQuery closest() method to get the closest ahref:

    $("#your-element").closest("a").css("color", "red");
    

    Or you can have a look at the parentsUntil method:

    $("#your-element").parentsUntil("#yourWrapper", "a").first().css("color", "red");
    

    Try it out here: http://www.lunarailways.com/demos/parents.html

    0 讨论(0)
提交回复
热议问题