Reddy
Reddy

Reputation: 1497

jQuery - Add class to last 2 elements only if length is more than 5

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");

FIDDLE


Upvotes: 4

Views: 7221

Answers (3)

Phoenix
Phoenix

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

Arun P Johny
Arun P Johny

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

Kyojimaru
Kyojimaru

Reputation: 2724

just add if statement to check the length/total of the li before you add the class

if($('#mymenu ul li').length > 5)
    $('#mymenu ul li:last-child').prev('li').andSelf().addClass("red");

FIDDLE

Upvotes: 1

Related Questions