Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
MOD
Dane Parchment
Treehouse Moderator 11,021 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.


Example:

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() {
     $('#box1').addClass("box");
});

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() {
     $('#box1').removeClass("box");
});

Which results in:

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

Hope that helps clear things up for you.