Adding or Removing Classes from an Element in JavaScript

Manipulating classes is a fundamental aspect of dynamic web development, enabling you to apply styles conditionally and create responsive user interfaces.

In this comprehensive guide, we'll explore different methods to add or remove classes from an element using plain JavaScript.

Method 1: Using the "classList" Property

The classList property provides a set of methods for adding, removing, and toggling classes on an element.

Adding a Class:

// Get the element by its ID
const myElement = document.getElementById('myElement');

// Add the class 'newClass' to the element
myElement.classList.add('newClass');

Removing a Class:

// Remove the class 'oldClass' from the element
myElement.classList.remove('oldClass');

Toggling a Class:

// Toggle the class 'active' on the element
myElement.classList.toggle('active');

The classList methods provide a convenient and concise way to modify classes on an element.

Method 2: Using the "className" Property

The className property contains a space-separated string representing the classes of an element. You can manipulate this string to add or remove classes.

Adding a Class:

// Add the class 'newClass' to the element using className
myElement.className += ' newClass';

Removing a Class:

// Remove the class 'oldClass' from the element using className
myElement.className = myElement.className.replace('oldClass', '');

This method is straightforward but has some limitations, such as potential issues with class names containing substrings of other class names.

Method 3: Using the "classList" Property with Spread Operator

If you want to add multiple classes at once without explicitly listing them, you can use the spread operator.

// Add multiple classes to the element using spread operator
myElement.classList.add(...['class1', 'class2', 'class3']);

This method is especially useful when you have an array of classes to add.

Method 4: Using "toggle" with a Condition

You can use a condition to add or remove a class based on a certain criterion.

// Toggle the class 'nightMode' based on a condition
const isNightMode = true;

if (isNightMode) {
    myElement.classList.add('nightMode');
} else {
    myElement.classList.remove('nightMode');
}

This approach is useful when you need to dynamically adjust classes based on runtime conditions.

Conclusion

Adding or removing classes from an element is a fundamental operation in web development.

Whether you use the classList property, className, spread operator, or conditionally toggle classes, each method has its use cases and considerations.

Choose the approach that best fits your project's requirements and coding style, ensuring that you can efficiently and accurately manipulate classes on elements for creating dynamic and responsive user interfaces.