If I execute the following snippet,
s = document.createElement('span');
console.log(s)
s.classList.add('foo');
console.log(s)
s.classList.remove('foo');
console.log(s)
I get this output:
<span></span>
<span class="foo"></span>
<span class></span>
Why is class
still there in the 3rd line? Does it serve any purpose? Or can I just consider it absent?
3
Answers
classList
property is used to manipulate the class names within theclass
attribute, but the attribute itself will still exist. To remove theclass
attribute itself, you can use theremoveAttribute()
The class attribute is always present in HTML elements, even if it doesn’t have any CSS class assigned to it.
In HTML, an element can have a class attribute without any specific classes assigned to it. When you use
classList.remove('foo')
, you are removing the specific classfoo
from the list of classes associated with the element. However, the class attribute itself remains, though without any classes.This behavior is part of how the HTML specification works, and it’s perfectly normal. The class attribute can be used to add multiple classes to an element, so even if you remove all classes from it, the attribute itself remains to allow you to add more classes later if needed. Though it doesn’t serve any specific purpose in this case, but it’s there to maintain the structure of the HTML element.
It is an attribute with no value. No more, no less. It is not really "special". It obeys the normal rules and for example can be matched by an attribute selector
The presence of a valueless
class
attribute does not do anything by itself. While it is possible that someone wrote a selector that only uses its presence:class
" is not a universal thing.So, overall it is possible in theory that
<span>
and<span class>
would behave differently. However, it is very unlikely that they would. Depending on what the code is trying to do with those it might be safe to consider them equivalent.