每个父级上每个第一个元素的jQuery选择器 [英] jQuery selector for each first element on every parent
问题描述
我有这样的HTML:
<div class="container">
<span class="iconset"></span> <!-- want to select -->
<span class="iconset"></span>
</div>
<div class="container">
<span class="iconset"></span> <!-- want to select -->
<span class="iconset"></span>
</div>
我需要使用以下命令选择每个.container
的第一个元素:
I need to select the first element of every .container
, using:
$(".container .iconset:first");
我只得到一个元素,第一个被发现.并使用
I get only one element, the first found. And using
$(".container .iconset");
我得到了所有四个要素.我不想检查索引是偶数还是奇数,因为以后可以添加更多的元素.
I get all 4 elements. I don't want to check the index for even or odd because more elements could be added later.
如何构建选择器以返回每个容器上的所有第一个元素?
How can I build a selector to return all first elements on every container?
推荐答案
此方法使用第一个孩子选择器,仅当.iconset
是其父项的第一个子项时才会选择.
This uses the first child selector, which will only select the .iconset
if it is the first child of its parent.
由于.iconset
是.container
的直接子代,因此它也使用>
子代选择器.
It also uses the >
children selector, since .iconset
is a direct child of .container
.
$(".container > .iconset:first-child");
您使用的是第一个选择器,它将整个匹配项缩小到第一个一个.
You were using the first selector, which narrows the entire matched set down to the first one.
这篇关于每个父级上每个第一个元素的jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!