How to get parent elements except some in native Js

3

Let's say I have:

 <section id="ele-section1">
    <div data-section="1">
        <div class="not_this">
            <div>
                <div class="ele2">
                    <div id="ele3">
                        <div class="ele4">
                            <div class="child">
                                <!-- Conteúdo -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

I want to 'grab' all elements that are parents of .ele4 except .not_this (I also want those above this).

I know that with the help of jQuery it could be done like this:

$('.ele4').parents().not('.not_this, body, html');

But I would like to do this feature only in native js. How to do?

    
asked by anonymous 24.06.2016 / 14:20

1 answer

3

You can use Element.matches that checks if an element has a certain CSS selector, or rather if it would be selected with a given CSS selector. If it is to use in older browsers there is a polyfill in that link above to make use of the logic of .matches .

So the function could look like this:

var getParents = (function() {
    function match(el, classes) {
        return classes.filter(function(css) {
            return el.matches(css);
        }).length != 0;
    }

    return function(from, not /*, not2, etc...*/ ) {
        var args = [].slice.call(arguments);
        var el = document.querySelector(args.shift());
        var parents = [];
        while (el = el.parentElement) {
            if (!match(el, args)) parents.push(el);
        }
        return parents;
    }
})();

console.log(getParents('.ele4', '.not_this', '#teste', 'body', 'html')); 
// dá [div#ele3, div.ele2, div, div, section#ele-section1]

And in this selection are left out element (s) with class not_this and also id teste , in addition to body and html

jsFiddle: link

    
24.06.2016 / 14:23