quelquecosa
quelquecosa

Reputation: 910

jQuery: select first matching descendant with a specific class

I have this HTML structure:

    <ul>
        <li>one</li>
        <li class="item">two</li>
        <li>three</li>
        <li class="item">four</li>

        <li id="click"> CLICK ME </li>
    </ul>

When I click on #click, I want to change the background color of ONLY the first child of ul that has a class of .item

I am trying this, but its not working:

    $('#click').click(function(){
        $("ul").first('.item').css('background-color','red');
    });

Upvotes: 7

Views: 8641

Answers (3)

vanval
vanval

Reputation: 1027

Another approach is $("li.item").first().css('background-color','red');

Upvotes: 0

hugerth
hugerth

Reputation: 171

 $('#click').click(function(){
    $("ul").children('.item').first().css('background-color','red');
});

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817208

First doesn't accept a selector, as you can see in the documentation. Use .find or .children with .first:

$("ul").children('.item').first().css(...);

This will reduce the set of selected elements to the first selected element.

If you have multiple lists and want to target the first li.item element of each of them, you can use .map:

$("ul").map(function() {
    return $(this).children('.item').get(0);
}).css(...);

Upvotes: 11

Related Questions