Kabir
Kabir

Reputation: 2156

How to replace the class using jQuery

Hi all. I am using jQuery and I want to replace the class on the DIV using jQuery. I know that I can replace the class like this:

$('#div').removeClass('first').addClass('second');

But, I can use this only when I know the first class name. In my case, I do not know the first class name because it is dynamic.

Upvotes: 3

Views: 148

Answers (5)

Suresh Atta
Suresh Atta

Reputation: 121998

Try this:

$('#div').removeAttr('class').attr('class', 'second');

Upvotes: 0

Adil
Adil

Reputation: 148110

You can use attr() to set the class, it will over write the previous class

$('#div').attr('class', 'second');

You can call removeClass without parameters

 $('#div').removeClass().addClass('second');

Upvotes: 6

amulamul
amulamul

Reputation: 390

The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

$("#div").toggleClass(second,function(index,first),TRUE)

Upvotes: 0

PSR
PSR

Reputation: 40318

When you call removeClass with no parameters this will remove all classes

$("#div").removeClass().addClass('second');

Upvotes: 4

Prasanth Bendra
Prasanth Bendra

Reputation: 32730

Try this :

$("#div").removeAttr('class');
$('#div').attr('class','second');

First line will remove the calss attribute, second will add a class with name second

Upvotes: 0

Related Questions