🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

Adding CSS Classes to Element Using jQuery .addClass() Method

Reading time 1 min
Published Jan 17, 2018
Updated Oct 2, 2019

jQuery addClass: Main Tips

  • jQuery .addClass() assigns a class to selected elements.
  • The function can be used on XML documents.
  • You may use .removeClass() method to remove classes added with jQuery .addClass().

How to Add Classes

The jQuery .addClass() method applies a class for each matched element. In the example below, an element changes color and size upon clicking a button:

Example
$("button").click(() => {
    $("div:first").addClass("div1");
});

There are two kinds of syntax you might use:

  • $("selector").addClass(class); - add a class you wish to apply. To add more than one class, separate them by spaces.
  • $("selector").addClass(function); - you might also name a function that returns a class name (or multiple) to be added.

Note: jQuery .addClass() method adds a class and does not replace the old ones.