How to add, remove and toggle class by JavaScript and jQuery?

Adding, removing and toggle class in HTML elements

To add, remove or update the class(es) attached to HTML elements, you may use the jQuery and JavaScript.

The jQuery has addClass, removeClass and hasClass methods that can be used for adding, removing or updating the classes.

Similarly, you may use the className and classList attributes of JavaScript, if you do not want to use the jQuery.

See the section below for demos by using jQuery and JavaScript.

A demo of using jQuery addClass method

In this example, a div element with simple text is created without assigning a class initially. As you click the button, the addClass method executes and adds a CSS class to that div element. See the demo and code below:

jquery addclass

See online demo and code

The complete code including jQuery, CSS, and markup:

 

You can learn more about addClass method of jQuery here.

A demo of jQuery removeClass method

In this example, the jQuery removeClass method is used for removing a class assigned to the div element initially. Click the button to delete the class:

jquery removeclass

See online demo and code

 

The code:

 

A demo of adding class by using JavaScript className attribute

In this example, the class is added to the button by using the className attribute of the JavaScript. The button classes are added from the Bootstrap framework, so the reference is included in the <head> section.

You can see, multiple classes are added by using the className attribute. Yoy may add one more classes separated by space as shown in the demo and code below:

javascript classname

See online demo and code

 

The Code:

 

A demo of removing class by using the className JS attribute

In this example, three Bootstrap classes are applied to the button initially i.e. btn, btn-success, and btn-block. As you click the button, the btn-block class is removed by using the JavaScript classList.remove.

That means the button size will be normal after removing the btn-block class. Have a look:

javascript remove classname

See online demo and code

The code for removing a class:

 

Using toggle attribute of JavaScript to add / remove a class

You may also use the toggle attribute to add/remove a class in an HTML element. If the class is already assigned, it will be removed and vice versa. See this demo:

javascript toggle

See online demo and code

 

The code:

 

A demo of jQuery toggle method

If you are using the jQuery, then $.toggle method can be used to add or remove a class in an element. Just like JS, if a class is already assigned it will be removed  and vice versa.

jquery toggleclass

See online demo and code

The code:

Also see: jQuery removeClass, jQuery toggle