Adding and Removing HTML Classes Upon Request With jQuery

By . Filed in Web Design

Adding new HTML class is a no-brainer; just open the HTML document, locate what you want to add, insert and name the class. But when it comes to building an interactive website that allows your visitors to engage with it, you might need to modify, insert, and remove the HTML classes upon request.

You can do this with jQuery. This example function below will add and remove my-new-class to the <div>.

// ## add class

// ## remove class

We can also use standard JavaScript code to add/remove HTML classes like so:

// add class
document.getElementById('elem').className = 'my-new-class';

// remove class
document.getElementById('elem').className = document.getElementByTag('div').className.replace( /(?:^|\s)my-new-class(?!\S)/g , '' )

The code as you can see above is less straightforward than when we are doing it with a JavaScript Framework jQuery. But if you don’t want to rely on a framework, you can always use a new JavaScript API called classList.

Using classList API

Similar to jQuery, classList provides a set of methods that allow us to modify HTML classes.

In a case where there is a div with multiple classes, we can retrieve the classes that are assigned in the div using classList.

var classes = document.getElementByID('elem').classList;

When we open the browser Console, we can see the list of the classes.

To add and remove class, we can use .add() and .remove().

var elem = document.getElementByID('elem');

// add class

// remove class

Adding multiple classes can also be done by separating each class with a comma:

elem.classList.add('my-new-class', 'my-other-class');

To check whether certain elements contain the specified class, we can use .contains(). It will return true if the class specified is present, and return false if it does not.


We can also toggle the class using .toggle(). The following code snippet shows how we bind the .toggle()method with a mouse click event.

var button = document.getElementById('button');
function toggle() {
button.addEventListener('click', toggle, false);

Check out the demo in action from the following links.

Final Thought

classList is a new native JavaScript API that is also introduced along with HTML5. It is neat and simple, and works in the following browsers: Firefox 3.6, Opera 11.5, and Chrome 8, and Safari 5.1. It is however absent in Internet Explorer 9 and below, so you may have to use the Polyfills when implementing classList API in Internet Explorer.

Further Resource


Thoriq is a writer for with a passion for web design and development. He is the author of Responsive Web Design by Examples, where he covered his best approaches in developing responsive websites quickly with a framework.



Comments are closed. Contact Us.