jQuery: target first class of div when it has a class of 'this'
<ul id="navigation">
<li class="this">example1</li>
<li>example2</li>
<li>example3</li>
</ul>
If I want to target the first child of #navigation (<li class="this">exam开发者_如何学Cple1</li>
) when it has a class of 'this' and add another class, how would I do that with jQuery?
Something like this? jQuery("#navigation:first-child.this").addClass("corner");
$("#navigation li:first-child.this").addClass("yournewclass");
See a working demo
An alternate method which doesn't use a chained selector (and so is in theory faster)
$('#navigation').children().first().filter('.this').addClass('corner');
which should also make the desiried logic obvious.
Use this selector
$("#navigation .this:first").addClass("corner");
This selector means: Select the first match from #navigation that has a class named "this".
I found that this code works: $("#navigation li:first-child.this").addClass("corner");
精彩评论