ssdesign
ssdesign

Reputation: 2821

How to add a class to a list item using jQuery

I have a vertical list where I am storing the current selected items index in a PHP session variable.

Now, when I come back to the same page, I want to apply a CSS Class to that particular list item.

Not sure how to set the class of a particular index in a list using jQuery.

I am doing something like this:

$('ul.selectable1 li').get(3).addClass('myselection');

The UL >li list has a class attached to it called "selectable1:

<ul id="items" class="selectable1">
  <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>

So if the Item-3 was stored in my session. I would like to make the list appear like this:

<ul id="items" class="selectable1">
  <li>Item 1</li>
  <li>Item 2</li>
  <li class="myselection">Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
</ul>

Upvotes: 0

Views: 79

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318508

Use .eq(2) - .get() returns a DOM element, not a jQuery object.

If you always want the third element you can also select it in the initial selector: $('ul.selectable1 li:eq(2)')

Upvotes: 4

Related Questions