[removed] How to get parent element by selector?

前端 未结 9 466
忘掉有多难
忘掉有多难 2020-12-02 16:31

Example:

....
<
相关标签:
9条回答
  • 2020-12-02 17:21

    You may use closest() in modern browsers:

    var div = document.querySelector('div#myDiv');
    div.closest('div[someAtrr]');
    

    Use object detection to supply a polyfill or alternative method for backwards compatability with IE.

    0 讨论(0)
  • 2020-12-02 17:22
    var base_element = document.getElementById('__EXAMPLE_ELEMENT__');
    for( var found_parent=base_element, i=100; found_parent.parentNode && !(found_parent=found_parent.parentNode).classList.contains('__CLASS_NAME__') && i>0; i-- );
    console.log( found_parent );
    
    0 讨论(0)
  • 2020-12-02 17:24

    Here's the most basic version:

    function collectionHas(a, b) { //helper function (see below)
        for(var i = 0, len = a.length; i < len; i ++) {
            if(a[i] == b) return true;
        }
        return false;
    }
    function findParentBySelector(elm, selector) {
        var all = document.querySelectorAll(selector);
        var cur = elm.parentNode;
        while(cur && !collectionHas(all, cur)) { //keep going up until you find a match
            cur = cur.parentNode; //go up
        }
        return cur; //will return null if not found
    }
    
    var yourElm = document.getElementById("yourElm"); //div in your original code
    var selector = ".yes";
    var parent = findParentBySelector(yourElm, selector);
    
    0 讨论(0)
提交回复
热议问题