Exploit
Exploit

Reputation: 6386

how to add and remove a class from a list of li elements?

if i have an li list like this:

<ul>
<li>first </li>
<li>second</li>
<li>third</li>
<li>fourth</li>
</ul>

How would i write the code in jquery to add a class to the li element , say , first without the class being added to the others?

i tried this but it of course adds to all li elements.

$(document).ready(function() {
$("ul li").click(function() {
if(!$("ul li").hasClass('active'))
{
$("ul li").addClass('active');
}
});

});

i want to be able to add the class active to only the li element that was click and remove all other exists who have active added to them. how would i do this? thanks

Upvotes: 1

Views: 668

Answers (1)

Jamiec
Jamiec

Reputation: 136239

one way

$("ul li").click(function() {
  var $this = $(this); // reference to the clicked li
  if(!$this.hasClass('active'))
  {
    $this.addClass('active');
    $('ul li').not($this).removeClass('active');
  }
});

Live example: http://jsfiddle.net/Xb9yx/

Another way

$("ul li").click(function() {
  var $this = $(this); // reference to the clicked li
  if(!$this.hasClass('active'))
  {
    $this.addClass('active').siblings().removeClass('active');
  }
});

Live example: http://jsfiddle.net/d5Sde/

This one one of those ones where there's probably a hundred ways to achieve the same thing.

Upvotes: 5

Related Questions