64
<div class="bestAnswerControl">
    <div id="ct100_contentplaceholder_lvanswer_control_divbestanswer"  
         class="IsBestAnswer"></div>
</div>

I want to add:

.bestanswer
{
    // some attribute
}

I want to replace class="IsBestAnswer" of div to class="bestanswer" by jquery. How do I do this?

I am using this approach:

$('.IsBestAnswer').addclass('bestanswer'); 

but it's not working.

irosenb
  • 828
  • 2
  • 13
  • 26
Nishant Kumar
  • 5,995
  • 19
  • 69
  • 95

3 Answers3

148
$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
  • 15
    If you call it with no parameters it will remove all classes from the element: e.g. $('#IsBestAnswer').removeClass().addClass('bestanswer'). – John Meyer Dec 29 '14 at 19:20
  • late 2012 the `Element.classList` introduced by browsers, that returns a `DOMTokenList` that have methods to manipulation of class attribute of a html element. – kankan256 Nov 19 '21 at 11:28
50

Instead of removeClass and addClass, you can also do it like this:

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
Tim
  • 881
  • 8
  • 19
13
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

jensgram
  • 31,109
  • 6
  • 81
  • 98