Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change class name of an element by jquery

Tags:

jquery

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

like image 514
Nishant Kumar Avatar asked Oct 18 '10 12:10

Nishant Kumar


People also ask

How do you change the class of an element?

To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)

How can I replace one class with another in jQuery?

To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.

How do you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


2 Answers

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

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

like image 88
Nikita Rybak Avatar answered Oct 04 '22 11:10

Nikita Rybak


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

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer'); 
like image 30
Tim Avatar answered Oct 04 '22 12:10

Tim