how to change class name of an element by jquery

Jquery

Jquery Problem Overview


<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.

Jquery Solutions


Solution 1 - Jquery

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

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Solution 2 - Jquery

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

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

Solution 3 - Jquery

$('.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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNishant KumarView Question on Stackoverflow
Solution 1 - JqueryNikita RybakView Answer on Stackoverflow
Solution 2 - JqueryTimView Answer on Stackoverflow
Solution 3 - JqueryjensgramView Answer on Stackoverflow