0

Possible Duplicate:
How to get nth jQuery element

I have this simple code:

<ul>
 <li>one</li>
 <li>two</li>
 <li>three</li>
</ul>

I know that my 2nd element should have a class active, how do I add this class?

this code won't work:

$('ul li').get(1).addClass('active')

I assume it is becuase it returns a dom element and not jquery element. but how do I do it right?

=======

Of course 2nd element is an example. I need each time to change the active class from a variable called theActiveClassNumber

Community
  • 1
  • 1
Alon
  • 7,618
  • 18
  • 61
  • 99

4 Answers4

3
$("ul li:nth-child(2)").addClass('active')

or

$("ul li:eq(1)").addClass('active')
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
0

get() returns a DOM element so you have to re-wrap in the jQuery object:

$( $('ul li').get(1) ).addClass('active');
leepowers
  • 37,828
  • 23
  • 98
  • 129
0

you can do like @Kanishka answer that work to, but you can try this one too, may be can help you,

$("ul li:nth-child(even)").addClass('active');
$("ul li:nth-child(odd)").addClass('active');
Khairu Aqsara
  • 1,321
  • 3
  • 14
  • 27
0

Not a direct answer to the question, but: If you want to get certain jQuery Object, you should use .eq() instead of .get().

Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74