如何在jQuery中选择不是特定元素子元素的元素?

时间:2014-12-09 12:06:16

标签: jquery jquery-selectors

我已经嵌套了这样的砌体网格:

<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>

如何选择列,这些列未嵌套在另一个Masonry网格中。结果集将包含第1,2,5和6列<?p>

我引用了两个砌体元素:

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? */

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

正确的解决方案是将其他类分配给嵌套的div

<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>

所以你可以选择:

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

但我会尝试这个

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

因为如果你的parentMasonry引用是正确的,你应该能够找到你需要的列

如果你需要,我已经尝试了另一种有效的解决方案

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

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

});

答案 2 :(得分:0)

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

答案 3 :(得分:0)

像这样的东西,将适用于嵌套列的任何级别

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

演示--> http://jsfiddle.net/tqn2kumc/