ReynierPM
ReynierPM

Reputation: 18660

change class on LI click

I need to dinamically assign a .selected class to the element where I click and also remove any other previous class asigned to the clicked element so I can change CSS class. Maybe this code:

$(this).click(function(){
  $(this).addClass('selected');
});

works but what happend if I click in any other LI? Any help to get this work?

EDIT: Ok see this code:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

By default none have any classes but I click in Item 2 then the HTML should transform on this one:

<ul>
  <li>Item 1</li>
  <li class="selected">Item 2</li>
  <li>Item 3</li>
</ul>

but once again if I click in Item 3 then the HTML should transform on this one:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li class="selected">Item 3</li>
</ul>

This is what I'm trying to do

Upvotes: 1

Views: 2993

Answers (3)

David Robertson
David Robertson

Reputation: 499

On my travels I discovered that it is not possible to addClass of 'active' to list items in when using bootstrap. So if you are reading this (as I was) wondering why this doesn't work when the classname is 'active' you need to choose something else.

Upvotes: 0

Ankush Jain
Ankush Jain

Reputation: 7049

First remove selected class from all li inside ul and then apply class to clicked li.

$('ul li').click(function(){
 $('ul li').removeClass('selected');
  $(this).addClass('selected');
});

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

$(selector).click(function(){
  $('.selected').removeClass('selected');
  $(this).addClass('selected');
});

With regards to the comment left by moonwave99 (below), if you only want to remove the selected class-name from those elements contained within the same parent element:

$(selector).click(function(){
  var that = $(this);
  that.parent().find('.selected').removeClass('selected');
  that.addClass('selected');
});

Though it's worth remembering what element you're clicking, and what the parent will be, for example, clicking on the a in the following HTML:

<ul>
    <li><a href="#">link text</a></li>
</ul>

Will look within the li for the other .selected elements, and so you should use:

$(selector).click(function(){
  var that = $(this);
  that.closest('ul').find('.selected').removeClass('selected');
  that.addClass('selected');
});

Upvotes: 4

Related Questions