Is it possible in JS to add to an html element some classes and remove some other classes in one line?

Viewed 43

Wonder if there's any functional equivalent of some_element.classList.add("some_class", "some_other_class).remove("some_other_other_class") line.

And I know that the .toggle() method would be a solution in some cases, but I wonder if there's a way to use exactly .add() and .remove() on one line.

2 Answers

Yes, you can use the classList.replace() method

element.classList.replace('some-class', 'new-class');

You could do something like this to add and remove multiple classes.

const header = document.getElementById('header');

const addClasses = ['foo', 'bar', 'hello'];
const removeClasses = ['class1'];

header.className = header.className.split(' ')
                         .filter(c => !removeClasses.includes(c))
                         .concat(addClasses).join(' ');

// to show the classes on the #header element
document.body.innerHTML = header.className;             
<h1 id="header" class="class1 class2 class3"></h1>

Related