How to get all parent elements except some

5

I'm in a situation where I need to get all the "parent" elements of a div, but I can not get all because it would not solve my problem. I wonder if I can put a limit on getting these elements. With an example it becomes clearer. Consider the structure:

<div class="all">
    <div class="1">
        <div class="2">
            <div class="3">
                <div class="4">
                <!-- Conteúdo -->
                </div>
            </div>
        </div>
    </div>
</div>

In this case I would like to get all the parent elements of the div with class 4 , with the exception of the all class div, but I also want all those above .all . Is it possible to do this via jquery?

    
asked by anonymous 23.06.2016 / 22:07

2 answers

10

Using the parents () function is simple, just put it inside the not () those elements you do not want:

var pais = $('.4').parents().not('.all, body, html');
pais.each(function() {
  console.log('classe do pai ' +$(this).prop("tagName")+ ': ' +$(this).prop('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><sectionclass="my-section">
    <div class="0">
        <div class="all">
            <div class="1">
                <div class="2">
                    <div class="3">
                        <div class="4">
                        <!-- Conteúdo -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
    
23.06.2016 / 23:11
4

You already have an answer with jQuery, here is one with native JavaScript. Remember that in HTML classes can not start with numbers, I think you have given numbers just for the example but I leave the warning in it.

var getParents = (function() {
    function hasClass(el, classes) {
        var elClassList = [].slice.call(el.classList);
        return elClassList.filter(function(_class) {
            return classes.indexOf(_class) != -1;
        }).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 (el == document.body) break;
            if (!hasClass(el, args)) parents.push(el);
        }
        return parents;
    }
})();

console.log(getParents('c4', 'all')); // [div.c3, div.c2, div.c1]
<div class="all">
    <div class="c1">
        <div class="c2">
            <div class="c3">
                <div class="c4">
                    <!-- Conteúdo -->
                </div>
            </div>
        </div>
    </div>
</div>

I made this function that receives as the first argument the class of the element where it starts, and then in the remaining arguments the other classes that do not want to catch . You can pass N arguments.

    
24.06.2016 / 10:38