Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: select first matching descendant with a specific class

Tags:

jquery

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');
    });
like image 386
quelquecosa Avatar asked Feb 15 '23 05:02

quelquecosa


1 Answers

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(...);
like image 114
Felix Kling Avatar answered Feb 17 '23 03:02

Felix Kling