Jordan Reiter
Jordan Reiter

Reputation: 21022

jQuery selector first matches in a set of elements

How do I select the first matches for a given selector over a set of elements?

For example, suppose I have the following HTML:

<ul>
<li>foo</li>
<li>bar</li>
<li class="interesting">red</li> 
<li class="interesting">yellow</li> 
<li class="interesting">blue</li>
</ul>

<ul>
<li>eggs</li>
<li>spam</li>
<li class="interesting">circle</li> 
<li class="interesting">square</li> 
<li class="interesting">triangle</li>
</ul>

<ul>
<li>tofu</li>
<li>bacon</li>
<li class="interesting">circle</li> 
<li class="interesting">square</li> 
<li class="interesting">triangle</li>
</ul>

I want the selector that retrieves the first .interesting element for each ul.

So in this case:

$("ul .interesting:magic-selector");

Would match the following:

<li class="interesting">one</li> 
<li class="interesting">red</li> 
<li class="interesting">circle</li> 

After trying out first-child (was Hmmmm...)

I'm trying the :first-child selector and it doesn't seem to work, at least not in Chrome.

Here's some sample code:

<ul>
<li>foo</li>
<li>bar</li>
<li class="interesting">red</li> 
<li class="interesting">yellow</li> 
<li class="interesting">blue</li>
</ul>

<ul>
<li>eggs</li>
<li>spam</li>
<li class="interesting">circle</li> 
<li class="interesting">square</li> 
<li class="interesting">triangle</li>
</ul>

<ul>
<li>tofu</li>
<li>bacon</li>
<li class="interesting">circle</li> 
<li class="interesting">square</li> 
<li class="interesting">triangle</li>
</ul>

<script type="text/javascript">
    $(document).ready(function () {
        $("ul .interesting:first-child").css('color', 'red'); // nothing happens
            // maybe I have the order wrong? only:
        $("ul .interesting :first-child").css('color', 'orange'); // nothing happens
        $("ul :first-child.interesting ").css('color', 'yellow'); // nothing happens
        $("ul :first-child .interesting ").css('color', 'green'); // nothing happens
        $("ul :first-child").css('color', 'gray'); // the control; it turns foo, eggs, and tofu gray
    });
</script>

Looks like maybe first-child only works to select the first child of a parent element, not the first matching selector of a parent element.

Barring that, I suppose I will have to do something like:

$("ul").each(function () {
    $(this).find(".interesting:first")…
});

Upvotes: 1

Views: 1742

Answers (4)

FreeCandies
FreeCandies

Reputation: 1113

$("ul .interesting:first")

should do the trick

Upvotes: 1

Munzilla
Munzilla

Reputation: 3855

Try using the first-child selector. http://api.jquery.com/first-child-selector/

Upvotes: 1

psx
psx

Reputation: 4048

:first-child

That'll be the magic selector you're looking for

Edit: beaten to it!

Upvotes: 0

Naftali
Naftali

Reputation: 146310

:first-child <-- try that magic-selector on for size.

Upvotes: 3

Related Questions