skobaljic
skobaljic

Reputation: 9614

How to select elements in jQuery that are not children of particular element?

I have nested Masonry grids like this:

<div class="masonry">
    <div class="column">1</div> <!-- <- This one -->
    <div class="column">2</div> <!-- <- This one -->
    <div class="masonry">
        <div class="column">3</div>
        <div class="column">4</div>
    </div>
    <div class="sidebar">
        <div class="column">5</div> <!-- <- This one -->
        <div class="column">6</div> <!-- <- This one -->
    </div>
</div>

How to select columns which are not nested inside another Masonry grid. Result set would hold columns 1, 2, 5 and 6?

I have references to both masonry elements:

var parentMasonry;
var childMasonry;
var elementsOutsideChild = parentMasonry.find('.column').not( /* What here? Not children of another .masonry? */ );
/* Or select all than apply filter? What is best to do? */

Upvotes: 1

Views: 66

Answers (4)

theLibertine
theLibertine

Reputation: 175

The right solution would be to assign other classes to the nested divs

<div class="masonry">
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="masonry">
        <div class="column col-exclude">3</div>
        <div class="column col-exclude">4</div>
    </div>
    <div class="sidebar">
        <div class="column">5</div>
        <div class="column">6</div>
    </div>
</div>

so you can go with:

$('.masonry').find('.column').not('.col-exclude');

but i would try with this

var elementsOutsideChild = parentMasonry.find('.column').not('.masonry')

because if your parentMasonry reference is correct, you should be able to find the columns you need

I have tried another working solution, if you need

$('.masonry').find('.column').not('.masonry .masonry .column').each(function(){

    var that = $(this);
    that.css({"color":"blue"});

});

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

Something like this, Will work with any level on nested columns

$('.masonry').find('.masonry').find('.column').addClass('nested');
var columns = $('.column').not('.nested');

Demo --> http://jsfiddle.net/tqn2kumc/

Upvotes: 0

Anarion
Anarion

Reputation: 1038

var elementsOutsideChild = parentMasonry.find('.column').not(function(){ return $(this).parents('.masonry').length !== 1 })

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

$('.masonry .column:not(.masonry .masonry .column)').css("color", "red");

JSFiddle: http://jsfiddle.net/t5njactk/1/

Upvotes: 2

Related Questions