Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  55] [ 6]  / answers: 1 / hits: 26703  / 8 Years ago, tue, may 3, 2016, 12:00:00

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?


More From » javascript

 Answers
30

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.


[#62325] Friday, April 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryder

Total Points: 473
Total Questions: 110
Total Answers: 91

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
;