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?
toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.
The Element. classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list. Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.
classList property The classList property has add() and remove() methods that allow passing multiple classes as arguments. Let's say we have a button with id value of button . To add multiple classes, you'll need to pass each class as a separate parameter to the add method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With