blue_zinc blue_zinc - 3 months ago 20
CSS Question

Vanilla JS: Check if element classList contains values from an array and remove them

I have a

div
as such:

<div class="modal" id="modal">


Occasionally, it may also have one more class from an array
["success", "error", "warning"]


How do I check if the element has any of the classes from that array and remove them, without removing the
modal
class?

What I'm doing is:

var modalAlertClasses = ['warning', 'error','success'];
var modal = document.getElementById('modal');
for (var i = 0; i < modal.classList.length; i++) {
if (modalAlertClasses.indexOf(modal.classList[i]) > -1) {
modal.classList.remove[modal.classList[i]];
console.log(modal.classList[i]);
}
}


But it doesn't work.

Answer

Your code uses the following

modal.classList.remove[modal.classList[i]];

but .classList.remove is a function, so should be written

modal.classList.remove(modal.classList[i]);