0

How do I add a css class to an Div element in JQuery? I have a DIV with a css class and the div contains a form. After clicking on submit I want the original css class to disappear and a new class to be added? I'm using JQuery as a Framework

6
  • 4
    Is there anything wrong with the jQuery documentation? Should not have been hard to find that in there. Commented Jul 7, 2009 at 10:11
  • Much easier to ask and get the answer than spend time reading. Commented Jul 7, 2009 at 10:12
  • The jQuery documentation is very good, but it's sometimes a little hard to quickly find what you're after. Commented Jul 7, 2009 at 10:14
  • @activa, use api.jquery.com Commented Jul 7, 2009 at 10:16
  • hmm, a simple "jquery+add class" in google would give instant gratification Commented Jul 7, 2009 at 10:43

4 Answers 4

10
$("#element_id").removeClass( "oldclass").addClass("newclass");
Sign up to request clarification or add additional context in comments.

Comments

4

To add a class, use addClass:

$('#myDiv').addClass("blah");

So upon your submit you can do something like:

$('#submit').click(function() {
    $('#myDiv').removeClass().addClass("blah");
});

Calling removeClass with no parameters removes all classes linked to that element. Alternatively, you can call removeAttr("style")

Comments

1

I think you can use

$("#target").addClass("newclass");

for adding the class to the elemet #target and

$("#target").removeClass("newclass");

to remove it.

If you dont know wether the class is already there or not you can use

$("#target").toggleClass("newclass");

if its there, it will be removed, and if its not there it will be added.

Comments

-1

Since OP didn't mention any ids I would go with a class selector and picking the first element in collection (which could be wrong, offcourse).

$(".OriginalClass").removeClass("OriginalClass").addClass("blah");

The original example was wrong, as the elements in the collection are regular objects and as such they don't have the removeClass and addClass methods.

The current example removes the class for all elements, which is still flawed, but in my opinion works better with what OP wanted.

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.