Explain Codes LogoExplain Codes Logo

Javascript CSS how to add and remove multiple CSS classes to an element

javascript
class-manipulation
javascript-techniques
web-development
Nikita BarsukovbyNikita Barsukov·Sep 30, 2024
TLDR

Toggle classes using classList in JS, as swift as the Flash:

// Superman in, Batman out: document.querySelector('.my-element').classList.add('class1', 'class2'); // Batman back, Superman takes a break: document.querySelector('.my-element').classList.remove('class1', 'class2');

This snappy script illustrates the basics of class adding and removal. It's as simple as swapping superheroes in Justice League!

Class manipulation techniques

A deeper dive into class manipulation uncovers multiple techniques suitable for various scenarios. Here they come:

Class cramming - Add multiple at once

let element = document.querySelector('.my-element'); element.classList.add(...['class3', 'class4', 'class5']); // Welcome to the class party!

Classy check - Verify before removal

if (element.classList.contains('class2')) { // Just making sure no class is wrongly expelled. element.classList.remove('class2'); }

Brutus' way - Direct assignment

If subtlety isn't your superpower, go the explicit path with className:

element.className += ' class6 class7'; // Hulk smash!

The old guard - Compatibility with IE8

Preserve support for old browsers by manipulating className:

element.className = element.className.replace(/\bclass7\b/g, ""); // Dutifully taking care of our elderly.

For a more automated approach, consider Babel to transpile your ES6-laced code for old browser compatibility.

Interactive dynamism via classes

Dynamic class adjustment in response to interactions can breathe life into your UI.

Attach event listeners

// Slap on a toggle on click, effectively creating a super hero quick-change booth. element.addEventListener('click', function() { this.classList.toggle('active'); });

Smoother extension

To gently append a class without disturbing existing ones:

element.className += ' new-class'; // Adding without subtracting means more is merrier!

Old-school setAttribute method

When dealing with legacy browsers sans classList, setAttribute can secure the deal:

element.setAttribute('class', element.className + ' new-class'); // Going "old school" is not always bad!

Slim-fitting scripts

Consider parting ways with external libraries for class manipulations to maintain a lean script. Vanilla JavaScript delivers a svelte solution for effective UI dynamics.

Class management alternatives and caveats

Beyond the classList, other methods and techniques exist for class management, each with its perks and warnings.

Direct Class Assignment

Through the class attribute:

// No beating around the bush, straight up! element.setAttribute('class', 'class8 class9');

Clone and Replace

In extreme cases, a duplicate, tamper, swap strategy looks something like this:

let newElement = element.cloneNode(true); newElement.className = 'class10 class11'; // Meet the clone, better than the original. element.parentNode.replaceChild(newElement, element);

Gotchas!

Watch those steps! With great power comes great responsibility. Be aware of accidental overwrites and ensure your page is fully loaded before your scripts awaken. Browser compatibility checks are crucial before unleashing your scripts in the wild.