Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 648
cluster1 Avatar asked May 03 '16 08:05

cluster1


People also ask

What does the element classList toggle () method do?

toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.

What does element classList do?

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.

Can you add multiple classes with classList add?

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.


1 Answers

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.

like image 134
Quentin Avatar answered Oct 02 '22 10:10

Quentin