3

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.

0

5 Answers 5

6

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');
Sign up to request clarification or add additional context in comments.

3 Comments

not sure it's cross-browser safe to use attr("class", ...).
The second option works perfectly correctly and is a suitable answer to the question asked - Downvotes should be supported by a reason IMHO otherwise it's unhelpful to everyone.
@MyStream yup.Seems like someone irritated with fast working answer by sir Adil :)
4

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

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

1 Comment

I have already voted you +1, but Adil's solution is also correct and I can accept only one answer :)
0

Try this :

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

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

1 Comment

if you remove class attribute how you can add class
0

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)

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.