views:

13

answers:

1

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 .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?

+4  A: 

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.

patrick dw
I remember seeing this, but I never dropped by to see what it does. Thanks! Also adding nth-child: http://api.jquery.com/nth-child-selector/
BrunoLM
@Bruno - You're welcome. And yes, nth-child could be used as well. :o)
patrick dw