How to get parent elements except for some in native Js

Asked

Viewed 77 times

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 the elements that are parents of .ele4 except for .not_this (I also want the above).

I know that with the help of jQuery:

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

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

  • This is Miguel! Take a look at this yesterday’s post here on the stack, I believe it’s exactly what you need :) http://answall.com/questions/136834/howto get everyone!

  • @the idea of this question arose from that :)

1 answer

3


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

So the function could be 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 outside element(s) with class not_this and also the id teste, beyond the body and of html

jsFiddle: https://jsfiddle.net/4n4od3a8/

  • 1

    Excellent @Sergio Thanks. I didn’t know. I also tried not to fetch '[data-section="1"]' and works well

  • Don’t pay attention to this, it’s just to ask this question and have here a solution adapted with your code as an alternative. https://jsfiddle.net/ks8hu650/11/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.