javascriptdom

How to get parent element by selector


Example:

<div someAttr="parentDiv. We need to get it from child.">
    <table>
        ...
        <td> <div id="myDiv"></div> </td>
        ...
    </table>
</div>

I want to get the parent by some selector from the inner div element (the one with the myDiv class).

How do I achieve that with plain JavaScript, without jQuery?

Something like:

var div = document.getElementById('myDiv');
div.someParentFindMethod('some selector');

Solution

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