How do I add a css class to an Div element in JQuery?

前端 未结 4 1389
一整个雨季
一整个雨季 2021-01-28 21:52

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 disapp

相关标签:
4条回答
  • 2021-01-28 22:23

    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.

    0 讨论(0)
  • 2021-01-28 22:27
    $("#element_id").removeClass( "oldclass").addClass("newclass");
    
    0 讨论(0)
  • 2021-01-28 22:30

    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")

    0 讨论(0)
  • 2021-01-28 22:32

    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.

    0 讨论(0)
提交回复
热议问题