jQuery API

.addClass()

.addClass( className ) Returns: jQuery

Description: Adds the specified class(es) to each of the set of matched elements.

  • version added: 1.0.addClass( className )

    classNameOne or more class names to be added to the class attribute of each matched element.

  • version added: 1.4.addClass( function(index, currentClass) )

    function(index, currentClass)A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.

It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

More than one class may be added at a time, separated by a space, to the set of matched elements, like so:

$("p").addClass("myClass yourClass");

This method is often used with .removeClass() to switch elements' classes from one to another, like so:

$("p").removeClass("myClass noClass").addClass("yourClass");

Here, the myClass and noClass classes are removed from all paragraphs, while yourClass is added.

As of jQuery 1.4, the .addClass() method's argument can receive a function.

$("ul li:last").addClass(function() {
  return "item-" + $(this).index();
});

Given an unordered list with five <li> elements, this example adds the class "item-4" to the last <li>.

Examples:

Example: Adds the class "selected" to the matched elements.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 8px; font-size:16px; }
  .selected { color:blue; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
  
<script>
  $("p:last").addClass("selected");
  </script>

</body>
</html>

Demo:

Example: Adds the classes "selected" and "highlight" to the matched elements.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
<script>
  $("p:last").addClass("selected highlight");
  </script>

</body>
</html>

Demo:

Example: Pass in a function to .addClass() to add the "green" class to a div that already has a "red" class.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { background: white; }
  .red { background: red; }
  .red.green { background: green; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
 <div>This div should be white</div>
 <div class="red">This div will be green because it now has the "green" and "red" classes.
   It would be red if the addClass function failed.</div>
 <div>This div should be white</div>
 <p>There are zero green divs</p>

<script>
  $("div").addClass(function(index, currentClass) {
    var addedClass;

    if ( currentClass === "red" ) {
      addedClass = "green";
      $("p").text("There is one green div");
    }
  
    return addedClass;
  });
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .addClass() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .addClass()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Rodrigo

    Isn’t there a “setClass” function to simply remove all element classes and set it a new one?

  • Rodrigo

    I just realize that I can use $(selector).attr(‘class’,'newClass’);

  • http://www.learningjquery.com/ Karl Swedberg

    Yep. You can also use $(selector).removeClass().addClass(‘newClass’);

  • Jared Jacobs

    The difference being that Rodrigo’s approach is just one DOM manipulation, so the browser is guaranteed not to draw and temporarily show an undesirable intermediate state.

    For this reason, I really wish jQuery had a replaceClass(“oldClass1 oldClass2″, “newClass1 newClass2″) to complement .addClass and .removeClass.

  • Anonymous

    The difference is also that Rodrigo’s approach will remove ALL classes from the element instead of being able to pick at a specific class with remove/add.

  • Rob

    AFAIK jQuery collects all DOM manipulations until the end of the chain and performs them at the same time. I would imagine it’s been optimised to perform the least number of actions on the DOM so the undesirable state may not ever occur.

  • http://www.ciftcioglumobilya.com mobilya

    Yep. You can also use $(selector).removeClass().addClass('newClass');

  • Bernd

    Be careful when trying subsequent jQuery Manipulation on Elements with classes which were added using addClass() as they are added AFTER the document loaded.

    I tried to add a class $(“#button”).click().addClass('collapse') and expected that $('.collapse').hide(); would work afterwards. As no element with a 'collapse' class existed when the document was loaded, this won't work. You could included a .collapse element in the original document and put it on display:none in the CSS. I am sure there are other ways to do it, but this worked for me.

  • http://www.ciftcioglumobilya.com/kose-takimlari.htm Ciftcioglumobilya

    Isn't there a “setClass” function to simply remove all element classes and set it a new one?

  • Sodalasit

    How would I use this to say….if div elements `rating` = 10 then add class 'bold' to that entire element.

  • Gijs

    Just use the real DOM underneath and a regex with .className?

  • Serge Toure

    Hi
    I think you must a class selector to that div tag and use it in your jquery.

  • Viperzenator

    most prob u can do so by $('p').addClass('myClass').delay(500).removeClass('myClass');
    try it out :)

  • Emilio Conti

    Didn't work for me.
    If it works for someone cancel this comment, please.
    If it doesn't work for anyone cancel Viperzenator's comment and please don't publish comments going “most prob” any longer.

  • Tapas Adhikary

    Add Class will add a class to the element . How to query the class back ? How to do getClass() ?

  • dxDennis

    var myClass = $('element').attr('class');
    Should do it.

  • Nipponese

    I don't understand why the addClass selector doesn't follow the name selector format at the initial selector. How can I use addClass to specific something like “.purchase_history_table tr.odd”?

  • Elanari

    Is it possible to add a class permanently to an element ? With this method, the DOM is changed only during the lifetime of the page, how could I make this change permanent ?

  • http://www.learningjquery.com/ Karl Swedberg

    You would have to store that change on the server somehow (in a database, possibly, using server-side code) or in a cookie.

  • Gcs363

    Seems to me you could just add a rule to the CSS to make the change “permanent”.
    Or are you looking to change the class of an element on-the-fly?

  • Anonymous

    You’re confusing selectors and adding a class to an object. You’re adding it to a specific element – so you’d want to get your TR object$(‘tr:first’).addClass(‘odd’) – this would then match your previous CSS for what you mentioned.Otherwise you’d also have to find its parent, and add the ‘purchase_history_table’ class to it too.

    Really you should be able to add classes to any jquery-selection of elements. So $(‘.purchase_history_table tr.odd’).addClass(‘blah’) would work. Though you’d probably want :o dd not .odd?

  • 2046

    the .removeClass exists:
    http://api.jquery.com/removeClass/

  • Myndian

    If you want to permanently add a class to an element, edit the source of the original HTML/PHP/whatever file and use <element class=”yourclass”>…

    Now, if you want to add a class to an element and have it maintain that state until you perform some action to remove that class from the element, and for some reason you want to use javascript to do that, you'd have to have a database set up, or at least a flatfile to store and recall the status of the class (active or inactive).</element>

  • AkshayTrenzy

    On pressing a button i want to add a new class to it after removing the previous class assigned to it.
    Like .removeClass() and then .addClass() – Here i am adding a boundary to the select box.
    Now the new class is being applied on select box and a change is seen but only in IE.
    This does not work in Mozilla, the previous class is not getting replaced. Any solutions?

  • Nandhakumar

    how to include multiple css inside jquery…. (i.e) $(#divi).css(position:absolute; color:#fff; );

    This is not working… Is it correct…? Suggestions needed immediately…. Thanks in Advance….

  • Silent

    hi
    you may have sorted this little problem out already but if you have not here we go

    $(“div”).css({“position”:”absolute”,”color”:”#fff”});

    this is the correct way: don't forget the curly brackets { } and each css reserved word and element needs to be surrounded by quotations ” “

  • http://twitter.com/wiresjr Jymbob

    Actually, the selector element does support this. See http://api.jquery.com/jquery/#selector-context for more info, but the format here would be something like:
    $('tr', '.purchase_history_table').addClass('foo');

  • Anonymous

    The more I read his comment, the more confused I am about what exactly he was asking :) Oh well!

  • Robinson00544

    Hi, how dose the function(index, class) use?i can’t get the class

  • http://twitter.com/dimazru Dmitry

    Why don`t work?

    $(“.a1″).click(function() {$(“#s1″).show();$(“.a1″).addClass(“a12″)})
    $(“.a12″).click(function() {$(“#s1″).hide();$(“.a12″).addClass(“a1″)})

  • http://twitter.com/dimazru Dmitry

    Why don`t work?

    $(“.a1″).click(function() {$(“#s1″).show();$(“.a1″).addClass(“a12″)})
    $(“.a12″).click(function() {$(“#s1″).hide();$(“.a12″).addClass(“a1″)})

  • Michael Landis

    Seems that would be $(foo).attr(“css”, “replacement-class”).

  • Michael Landis

    Seems like I can't read threads. ;-)

  • Reid

    In a test in Foxfire 3.6.12 I see that adding a class multiple times to a span only results in one copy of the class being added. So it apparently adds only if it doesn't exist already. If this is universally true, then the documentation should ideally point that out.

  • Lolol232

    Your common sense should ideally point that out.

  • LFA

    Hello, i'm trying to switch a class dinamically on a div element but its not working properly. Here's my code

    $('.slide_title_plus').click(function(){
    $(this).next('.slide_content').slideToggle();
    $(this).removeClass('slide_title_plus');
    $(this).addClass('slide_title_minus');
    return false;
    });

    $('.slide_title_minus').click(function(){
    $(this).next('.slide_content').slideToggle();
    $(this).removeClass('slide_title_minus');
    $(this).addClass('slide_title_plus');
    return false;
    });

    When I click a “slide_title_plus” class element, i want it to switch to the “slide_title_minus” class. The first time it works, but then I click on the same switched “slide_title_minus” element and it doesn't turn back into the first class

    Any ideas?

  • LFA

    Hello, i'm trying to switch a class dinamically on a div element but its not working properly. Here's my code

    $('.slide_title_plus').click(function(){
    $(this).next('.slide_content').slideToggle();
    $(this).removeClass('slide_title_plus');
    $(this).addClass('slide_title_minus');
    return false;
    });

    $('.slide_title_minus').click(function(){
    $(this).next('.slide_content').slideToggle();
    $(this).removeClass('slide_title_minus');
    $(this).addClass('slide_title_plus');
    return false;
    });

    When I click a “slide_title_plus” class element, i want it to switch to the “slide_title_minus” class. The first time it works, but then I click on the same switched “slide_title_minus” element and it doesn't turn back into the first class

    Any ideas?

  • http://twitter.com/aceDchichong potogas

    ok

  • http://nateferrero.com/ Nate

    When you call $('.slide_title_minus').click(function); jQuery searches for all elements with that class, and tries to assign a click handler to them. However, when that code runs there is no .slide_title_minus, so the event handler is never bound. Look up the jQuery function called live()

  • http://twitter.com/chrisimrie Christopher Imrie

    great feature

  • Chenru8891

    呵呵 看不懂

  • http://twitter.com/zeus3213 Dong

    it's useful func

  • Davidxiaozhi

    I like this demo,it is a nice func.

  • http://www.whitelogicsolutions.com Ash Singh

    I am trying to add a class to li with similar class for rest of li, on click event, but whenever i do that it does add class for a moment then load the page, I have used the following code.

    $('.navLi a').click(function(){
    $(this).addClass('selected');
    });

    Can Any one help me out…..thanks!!!