开发者

jQuery: target first class of div when it has a class of 'this'

开发者 https://www.devze.com 2023-02-18 20:26 出处:网络
<ul id=\"navigation\"> <li class=\"this\">example1</li> <li>example2</li>
<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");

0

精彩评论

暂无评论...
验证码 换一张
取 消