I have a HTML like this:
<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>
I need to select the first element of every .con开发者_运维知识库tainer
, 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?
This uses the first child selector, which will only select the .iconset
if it is the first child of its parent.
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.
精彩评论