我有一个像这样的 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
的第一个元素,使用:
$(".container .iconset:first");
我只得到一个元素,即第一个找到的元素。并使用
$(".container .iconset");
我得到了全部 4 个元素。我不想检查索引的偶数或奇数,因为稍后可以添加更多元素。
如何构建一个选择器以返回每个容器上的所有第一个元素?
最佳答案
这使用 the first child selector ,如果 .iconset
是其父级的第一个子级,则只会选择它。
它还使用 >
子选择器,因为 .iconset
是 .container
的直接子级。
$(".container > .iconset:first-child");
您正在使用the first selector ,这会将整个匹配集缩小到第一个。
关于每个父元素上每个第一个元素的 jQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3968853/