这似乎是一个简单的问题,但我有一些困难,以解决这个问题。给出的例子是一个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:42:17
你可以用这个:
$('#root').find('.child').filter(function(){
return $(this).parents('.parent').length <= 1;
}).css('font-weight', 'bold');它检查div的父级数,如果它低于或等于1,则返回子元素。
小提琴:http://jsfiddle.net/akwPb/
https://stackoverflow.com/questions/24310501
复制相似问题