JavaScript AJAX Basics (retiring) AJAX and APIs Adding jQuery

removeClass and addClass

What does .removeClass("selected") and .addClass("selected")

do and mean? 1- what is removeClass 2- what is addClass 3- what is selected?

1 Answer

Dane Parchment
Dane Parchment
9,745 Points

These do exactly what they say they are doing.

addClass() - Adds a css class to the element calling the method.

removeClass() - Removes a css class from the element calling the method.

The parameter within the method is literally the css class name that is being added or removed.


Let's say we have the following html and css, a div with an id of box1 and a css class for a basic box.

.box {
   width: 200px;
   height: 200px;
<div id="box1">I am a box.</div>

We want to programmatically add a css class to it, that applies that general box styling to it. So using JQuery we can use the addClass method to add the box class to the html element.

$(document).ready(function() {

Will result in the html being rendered as:

<div id="box1" class="box">I am a box.</div>

If we wanted to remove the class we could just use the removeClass method instead.

$(document).ready(function() {

Which results in:

<div id="box1">I am a box.</div>

Hope that helps clear things up for you.