如何选择仅限第一个级别.block而不选择任何子级?
$('.block:not("Children of this here")')
< -
<div class="block"> <!-- this -->
<div class="block"> <!-- not this -->
<div class="block"> <!-- not this -->
</div>
</div>
</div>
<div class="block"> <!-- and this -->
<div class="block"> <!-- not this -->
<div class="block"> <!-- not this -->
</div>
</div>
</div>
答案 0 :(得分:9)
如果该样本标记具有父元素,例如下面。如果不是,则父级将为body
,如果它是有效的HTML。
<div id="parent">
<div class="block">
<div class="block">
<div class="block">
</div>
</div>
</div>
</div>
$('#parent > .block').css({ border: '1px solid red' });
答案 1 :(得分:2)
您可以使用:first
选择器仅选择第一个匹配的.block
元素:
$('.block:first')
这是有效的,因为jQuery按文档顺序匹配元素。最外面的.block
元素将是.block
匹配的第一个元素,:first
将过滤仅返回它。
请注意,:first
与:first-child
不同。
编辑:为了响应您的更新,您可以编写以下内容,只有在所有元素都嵌套在三个深层时才能生效:
$('.block:note(:has(.block .block))')
您可以使用函数调用编写更强大的解决方案:
$('.block').not(function() { return $(this).closest('.block').length; })
这将找到所有.block
元素,然后删除任何具有祖先匹配.block
的匹配元素。 (如果您愿意,可以将closest
替换为parent
。
答案 2 :(得分:1)
$('#parent').children('.block');
请参阅.children() jQuery参考。
答案 3 :(得分:0)
试试这个:
$("div.block:first").<what you want to do>
编辑:删除空格。谢谢: - )....现在它应该是好的。
HTH