[removed] How to get parent element by selector?

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

Example:

....
<
9条回答
  •  南方客
    南方客 (楼主)
    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);
    

提交回复
热议问题