Salvatore Fucito
Salvatore Fucito

Reputation: 355

How to remove a specific class on the clicked control?

I'm trying to remove a specific class on the clicked control, in particular I've this html structure:

<div id="resource">
   <div class="selected"></div>
   <div class="selected"></div>
</div>

this is my code:

$(document).on('click', '.selected', function() {
if ($(this).hasClass('selected')) {
  $(this).removeClass('selected'); //remove the specific class
} else
{
  $('#resource .selected').removeClass('selected'); //remove class of all control
$(this).addClass('selected'); //add class to the clicked control
}
});

and this is the css class:

.selected {
 background-color: red;
}

How you can see if I click on a div the class is added correctly, but if I've a div with .selected class already set and click on the div without this class the code doesn't remove the class of other div. Why??

this is the jsfiddle.

Upvotes: 1

Views: 72

Answers (3)

sundar
sundar

Reputation: 408

<div id="resource">
   <div class="container"></div>
   <div class="container"></div>
</div>   


 $(document).on('click', '.container', function() {
      $(this).toggleClass('selected');
    })

change ur 'selected' div class names to 'container' or watever u want. add click listener for those divs having 'container' or whatever name u hav given for tat div

Upvotes: 0

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

You can make this more simple by adding an extra class. See this fiddle. The error is that the selected class gets removed. Which means your click event is also removed. Using 2 classes can remedy this.

Javascript

$(document).on('click', '.item', function() {
   $('.item').removeClass('selected');
   $(this).addClass('selected'); //add class to the clicked control
});

Html

<div id="resource">
   <div class="item">test</div>
   <div class="item">test</div>
</div>

Upvotes: 0

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

Your click event works for only for .selected class. You should use #resource div click instead of .selected. Try like following.

$(document).on('click', '#resource div', function() {
   if ($(this).hasClass('selected')) {
       $(this).removeClass('selected');
   } else
   {
      $('#resource .selected').removeClass('selected'); 
      $(this).addClass('selected');
   }
});

UPDATED FIDDLE

Upvotes: 2

Related Questions