st88 st88 - 7 months ago 16
Javascript Question

Checking classList with contains if a class exists before add or remove?

A colleague of mine insists that it is important to check first if a class exists on an element before adding or removing it.

Therefore he has lot of constructs in his code like this:

if (element.classList.contains('info')) {
element.classList.remove('info');
}

if (!element.classList.contains('hint')) {
element.classList.add('hint');
}


I personally guess that nothing would happen if one leaves the check with .contains( ) out.

Shall mean:

If the class isn't there nothing is removed. The statement is just meaningless.

If the class is already there then nothing is added.

Is my colleague right with his insisting on the check because not checking could result in some trouble?

Or can I forget about that checking?

Answer

Explicitly checking is pointless. It is a waste of time and bloats your code.

Those checks are effectively built-in to the add and remove class methods.

If you try to add a class that the element is already a member of, then classList.add will ignore it.

If you try to remove a class that the element isn't a member of, then classList.remove will do nothing.