给定一个具有许多后代级别的jquery对象,如何排除某些后代及其后代?假设要排除的元素的顶部节点上有一个类(在这种情况下为.foo
),并且您的jquery对象是下面的div1
。
编辑:澄清:我想排除所有.foo
的后代,而不仅仅是直系子代。
$('#button1').click(function() {
var selector = '#test ' + $('#input1').val();
var numberElements = $(selector).length;
$('#numberElements').text(numberElements);
var elementsAsCommaSeparatedList = _.pluck($(selector), 'id');
$('#elementList').text(elementsAsCommaSeparatedList.join(', '));
});
#input1 {
width: 230px;
font-size: 16px;
font-weight: bold;
}
#numberElements,
#elementList {
color: green;
font-weight: bold;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="input1">Please supply a selector... $('<input id="input1" value="div:not(.foo, .foo *)"></label>')
<button id="button1">Apply Selector</button>
<div>(default value is from @DaniP's answer)</div>
<div id="result"><span>Number of elements selected: </span><span id="numberElements">0</span></div>
<div>
<span>Elements selected (by id):</span>
<span id="elementList"></span>
</div>
<div id="test">
<div id="div1">
<div id="div2">
<div id="div4">
<div id="div8"></div>
<div id="div9"></div>
</div>
<div id="div5" class="foo">
<div id="div10"></div>
<div id="div11"></div>
</div>
</div>
<div id="div3">
<div id="div6">
<div id="div12"></div>
<div id="div13"></div>
</div>
<div id="div7" class="foo">
<div id="div14"></div>
<div id="div15"></div>
</div>
</div>
</div>
</div>
最佳答案
jQuery查询
使用Jquery,您可以在:not
选择器上使用多个参数,这种方式很容易排除.foo
和子元素:
$('div:not(.foo, .foo *)')
示例片段
$('div:not(.foo, .foo *)').css('border-color','blue')
div {
padding-left:20px;
margin:5px;
border:thin red solid;
}
.foo {
background:rgba(0,0,0,.1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
DIV1
<div>
DIV2
<div>
DIV4
<div>DIV8</div>
<div>DIV9</div>
</div>
<div class="foo">
DIV5
<div>DIV10</div>
<div>DIV11</div>
</div>
</div>
<div>
DIV3
<div>
DIV6
<div>DIV12</div>
<div>DIV13</div>
</div>
<div class="foo">
DIV7
<div>DIV14</div>
<div>DIV15</div>
</div>
</div>
</div>
但是CSS不允许这样做,refer to this answer。
的CSS
在CSS上,您需要定位所有非
.foo
的div,但还要再次覆盖.foo
的子元素:div:not(.foo) {
border-color:blue;
}
div.foo * {
border-color:red;
}
示例片段
div {
padding-left:20px;
margin:5px;
border:thin red solid;
}
.foo {
background:rgba(0,0,0,.1)
}
div:not(.foo) {
border-color:blue;
}
div.foo * {
border-color:red;
}
<div>
DIV1
<div>
DIV2
<div>
DIV4
<div>DIV8</div>
<div>DIV9</div>
</div>
<div class="foo">
DIV5
<div>DIV10</div>
<div>DIV11</div>
</div>
</div>
<div>
DIV3
<div>
DIV6
<div>DIV12</div>
<div>DIV13</div>
</div>
<div class="foo">
DIV7
<div>DIV14</div>
<div>DIV15</div>
</div>
</div>
</div>
关于javascript - CSS选择器排除某些后代及其jQuery对象的后代?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43008463/