Add or Remove HTML classes in Jquery

Add or Remove HTML classes in Jquery

Adding new HTML class is a no-brainer

You can do this with jQuery. This example function below will add and remove my-new-class to the <div>.
// ## add class
$(‘div’).addClass(‘my-new-class’);

// ## remove class
$(‘div’).removeClass(‘my-new-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.

Recommended Reading: Obtaining User Location With HTML5 Geolocation API

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;
console.log(classes);
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
elem.classList.add(‘my-new-class’);

// remove class
elem.classList.remove(‘my-new-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.
elem.classList.contains(‘class-name’);
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() {
elem.classList.toggle(‘bg’);
}
button.addEventListener(‘click’, toggle, false);
Check out the demo in action from the following links.


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top