Modifying CSS classes in JavaScript involves manipulating the classList property of DOM elements. Here's a basic guide on how to do it:
Adding a CSS Class:
You can add a CSS class to an element using the classList.add()
method.
// Get the element
const element = document.getElementById('yourElementId');
// Add a CSS class
element.classList.add('yourClassName');
Removing a CSS Class:
Removing a class is done using classList.remove()
.
// Get the element
const element = document.getElementById('yourElementId');
// Remove a CSS class
element.classList.remove('yourClassName');
Toggling a CSS Class:
You can toggle a class on and off using classList.toggle()
.
// Get the element
const element = document.getElementById('yourElementId');
// Toggle a CSS class
element.classList.toggle('yourClassName');
Checking if an Element has a Class:
To check if an element has a specific class, you can use classList.contains()
.
// Get the element
const element = document.getElementById('yourElementId');
// Check if the element has a CSS class
if (element.classList.contains('yourClassName')) {
// Do something
}
Modifying Multiple Classes:
You can also work with multiple classes at once, separating them by spaces.
// Get the element
const element = document.getElementById('yourElementId');
// Add multiple classes
element.classList.add('class1', 'class2', 'class3');
// Remove multiple classes
element.classList.remove('class1', 'class2');
// Toggle multiple classes
element.classList.toggle('class1', 'class2');
Remember to replace ourElementId
with the ID of the HTML element you want to manipulate, and yourClassName
with the class name you want to add, remove, or toggle.