1

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

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

3 Answers3

4

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');
});
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 1
    I'd just narrow the search to `$('.selected', $(this).parent())` in case there are more lists in the page. – moonwave99 Sep 04 '12 at 19:33
  • @david-thomas see my edited post, is this the same as you leave on your comments? – ReynierPM Sep 04 '12 at 19:39
  • @ReynierPM, the last of the code in the answer should do what you require. – David Thomas Sep 04 '12 at 19:41
  • As far as a bug-report goes, that doesn't help. What doesn't work? Can you show what you're working with in [JS Fiddle](http://jsfiddle.net/)? Just a demo, so I can see what's going on? – David Thomas Sep 04 '12 at 20:30
0

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');
});
Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
0

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.

David Robertson
  • 479
  • 7
  • 17