这似乎是一个简单的问题,但我有一些困难,以解决这个问题。给出的例子是一个SSCCE和我有一个更大的问题,这试图解决。为了使其工作,查询必须不包含任何直接子选择器(>),因为dom树比这个示例要复杂一些。
我在这里的目标是选择没有在包含类的父级下面的所有子级。在本例中,我尝试选择2 div容器-- hello和world,而不是foo和bar。
这里有一个柱塞,里面有你的方便代码。http://plnkr.co/edit/4zsKAFts5X7X2kLADj2V?p=preview
使用此HTML:
<div id="root" class="parent">
<div>
<div class="child">hello</div>
<div class="child">world</div>
</div>
<div class="parent">
<div>
<div class="child">foo</div>
<div class="child">bar</div>
</div>
</div>
</div>这个Javascript:
var root = $('#root');
$(':not(.parent) .child', root).css('font-weight', 'bold');我看到了这样的结果:
hello world foo bar
但我想得到的是
hello world foo 条形
重申一下,我希望获得类child的所有元素,这些元素没有从给定节点开始具有类parent的父元素(在本例中是#root)。
发布于 2014-06-19 15:43:43
var root = $('#root');
$('.child', root).not($("#root .parent .child")).css('font-weight', 'bold');jsFiddle实例
发布于 2014-06-19 15:36:54
它可能不太漂亮,但你可以这样做:
$('#root').find('.child').filter(function(){
if($(this).parents('.parent').first().attr('id') === 'root'){
return 1;
}
else{
return 0;
}
}).css('font-weight', 'bold');http://jsfiddle.net/PDZL8/
发布于 2014-06-19 15:43:53
JSFiddle:http://jsfiddle.net/TrueBlueAussie/78G6N/3/
var root = $('#root');
$('#root').find('.child').filter(function(){
return $(this).closest('.parent').is(root);
}).css('font-weight', 'bold');我还改进了j08691的解决方案,使其使用所提供的根节点,而不是复制选择器(它不是可移植的):
http://jsfiddle.net/TrueBlueAussie/78G6N/4/
var root = $('#root');
$('.child', root).not(root.find(".parent .child")).css('font-weight', 'bold');https://stackoverflow.com/questions/24310501
复制相似问题