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?
Does it serve any purpose?
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
[class] {
font-size: 2em;
}
[class="foo"] {
text-decoration: underline;
}
.foo {
color: red;
}
<span>
A
</span>
<span class>
B
</span>
<span class="foo">
C
</span>
Or can I just consider it absent?
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.