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');
});
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(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With