When you need to add a class name to an element using jQuery, you can use the addClass()
method.
The addClass()
method can accept multiple class names as its parameter, separated by a space:
addClass("newClass otherClass");
// adds newClass and otherClass to all matching elements
The addClass()
method can be used together with the removeClass()
method so you can change elements’ classes from one another.
Here’s an example of changing a <div>
element’s classes. You need to select the right element using jQuery selector $()
method as follows:
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>jQuery change class tutorial</h1>
<div class="example">The first DIV element</div>
<div class="example">The second DIV element</div>
<script>
$(".example").addClass("myClass").removeClass("example");
</script>
</body>
In the example above, the two <div>
elements’ classes will be changed from example
to myClass
.
You can also add and remove multiple classes at once:
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>jQuery change class tutorial</h1>
<div class="example noClass">The first DIV element</div>
<div class="example noClass">The second DIV element</div>
<script>
$(".example")
.addClass("myClass otherClass")
.removeClass("example noClass");
</script>
</body>
Keep in mind that you don’t need to add any dot .
to the class names you want to add or remove. Some people unintentionally add dots before the class name as follows:
$(".example")
.addClass(".myClass .otherClass")
.removeClass(".example .noClass");
While the addClass()
method will work as intended, the removeClass()
method will fail to remove the classes, but you won’t get any error message.