In order to add a class on a click event to a button, you could do something like this:
const btnAddClass = document.getElementById('btnAddClass');
btnAddClass.addEventListener('click', (e) => {
btnAddClass.classList.add('blue');
});
In order to remove a class, the code is quite similar. Instead of calling the add() method on the classList property of an element, we need to call the remove() function:
btnAddClass.classList.remove('blue');
A live example can be found here:
https://jsfiddle.net/dwome9yz/
If your ultimate goal is to make some sort of 'active' element be the only one with the class enabled from a list of buttons, you could do something along the lines of this, to get rid of all the 'active' elements first:
const removeActiveClass = () => {
const activeElements = document.getElementsByClassName('blue');
for (const activeElement of activeElements) {
activeElement.classList.remove('blue');
}
};
domElement.addEventListener('click', (e) => {
removeActiveClass(); // Call this first to remove the 'blue' class from all other elements
btnAddClass.classList.add('blue');
});
A live example can be found here:
https://jsfiddle.net/dpzLn1tj/
A simplified approach of the code posted above would be to use the same click event handler for all the buttons and only add the class to the button that was clicked using the target property of the event argument (Event.target) that is passed down during the click event and to remove the class for all the other elements:
const removeActiveClass = () => {
const activeElements = document.getElementsByClassName('blue');
for (const activeElement of activeElements) {
activeElement.classList.remove('blue');
}
};
const onClick = (e) => {
removeActiveClass();
e.target.classList.add('blue');
};
document.getElementById('btnAddClass').addEventListener('click', onClick);
document.getElementById('btnRemoveClass').addEventListener('click', onClick);
Live examples can be found here:
https://jsfiddle.net/dpzLn1tj/1/
https://jsfiddle.net/27c1n0wL/