Reputation: 1497
How can I add CSS class to last 2 <li>
elements only the parent <ul>
has more than 5 <li>
elements.
HTML
<div id="mymenu">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</div>
jQuery
$('#mymenu ul li:last-child').prev('li').andSelf().addClass("red");
Upvotes: 4
Views: 7221
Reputation: 333
You can count the children using:
$('#mymenu ul').children().length
,
basically:
if($('#mymenu ul').children().length > 5)
$('#mymenu ul li:last-child').prev('li').andSelf().addClass("red");
Upvotes: 2
Reputation: 388326
You can use a conditional approach
//cache the lis since we need to use it again
var $lis = $('#mymenu ul li');
//check if there are more than 5 elements
if ($lis.length > 5) {
//if so get the last 2 elements and add the class
$lis.slice(-2).addClass("red");
}
Demo: Fiddle
Upvotes: 1