How can I remove a class from an element using JavaScript?

How can I remove a class from an element using JavaScript?

Please provide a solution that only uses JavaScript, as I’m not familiar with jQuery and cannot use it. I’m looking for guidance on how to remove class in JavaScript.

Hi,

For this, you can use classList.remove()

This is the most straightforward and modern way to remove a class from an element.

// Select the element
const element = document.getElementById('yourElementId');
// Remove the class
element.classList.remove('yourClassName');

You can also directly manipulate the class attribute of the element. This method requires you to manage the entire class string.

// Select the element
const element = document.getElementById('yourElementId');
// Get current classes and remove the desired class
let currentClasses = element.getAttribute('class');
currentClasses = currentClasses.replace('yourClassName', '').trim(); // Remove the class and trim extra spaces
// Set the new class list
element.setAttribute('class', currentClasses);

Alternatively, you can directly change the className property of the element. This method will replace all classes if you assign a new string, so use it carefully.

// Select the element
const element = document.getElementById('yourElementId');
// Get current classes
let currentClasses = element.className;
// Remove the specific class
currentClasses = currentClasses.replace('yourClassName', '').trim(); // Remove the class and trim extra spaces
// Set the updated className
element.className = currentClasses;

Each the methods effectively removes a specified class from the element. The first option (classList.remove()) is the most recommended due to its simplicity and safety.