Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between className and classList

Which one of the following should be preferred under what circumstances?

btnElement.classList.add('btn');

btnElement.className = 'btn';
like image 246
Srishti Avatar asked Feb 13 '26 21:02

Srishti


1 Answers

Using "classList", you can add or remove a class without affecting any others the element may have. But if you assign "className", it will wipe out any existing classes while adding the new one (or if you assign an empty string it will wipe out all of them).

Assigning "className" can be a convenience for cases where you are certain no other classes will be used on the element, but I would normally use the "classList" methods exclusively.

And "classList" also has handy "toggle" and "replace" methods.

https://teamtreehouse.com/community/difference-between-classlist-and-classname

like image 171
Oleh Martemianov Avatar answered Feb 15 '26 11:02

Oleh Martemianov