nick
nick

Reputation: 1246

jquery & css target nth li with varaible instead of a number

I am using jQuery to add a class to a li in my ul. This is the code:

$('ul').children('li:eq( '2' )').addClass('active'); 

How can I replace the "2" with a variable that is dynamic? My code below does not work. I think its a syntax issue any advice?

var count = 2;
$('ul').children('li:eq( 'count' )').addClass('active'); 

Upvotes: 0

Views: 32

Answers (2)

Satpal
Satpal

Reputation: 133403

You need to concatenate your variable.

$('ul').children('li:eq( ' + count +' )').addClass('active');

However you can use $.fn.eq()

Reduce the set of matched elements to the one at the specified index.

 $('ul').children('li').eq(count).addClass('active');

Upvotes: 3

Gary Storey
Gary Storey

Reputation: 1814

You need to correctly add the count variable:

var count = 2;
$('ul').children('li:eq( ' + count + ' )').addClass('active'); 

Upvotes: 1

Related Questions