开发者

jQuery selector for each first element on every parent

开发者 https://www.devze.com 2023-01-20 09:08 出处:网络
I have a HTML like this: <div class=\"container\"> <span class=\"iconset\"></span> <!-- want to select -->

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号