Gowri
Gowri

Reputation: 16845

remove class jquery

I am having two div tags . i like to add class on click event for current div . But after that, when i click second div , both the div has the class. how to remove class for previous div?

<div title="a1"></div>

<div title="a1"></div>

$('[title:a1]').click(function() {

   $(this).addClass('current');

}); 

where should i wright remove class ?

Upvotes: 1

Views: 671

Answers (2)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

You probably need to remove the class from ALL elements first.

  $('div[title=a1]').click(function() {
       $('div[title=a1]').removeClass('current'); //remove current fom all divs
       $(this).addClass('current'); //ad it to current div only
   }); 

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630607

You need = in your attribute-equals selector:

$('[title=a1]').click(function() {
   $(this).addClass('current');
}); 

Note, you should use something like div[title=a1] instead here...anything to narrow that expensive selector down.


To remove the current class from the previously selected one, just do this:

$('[title=a1]').click(function() {
   $('.current[title=a1]').removeClass('current');
   $(this).addClass('current');
}); 

Upvotes: 5

Related Questions