Search code examples
javascripthtmldomchromium

Is there any reason why the "class" attribute stays in an HTML tag even after removing last class via classList.remove?


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?


Solution

  • 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:

    1. It would depend on the particular HTML + CSS/JavaScript application. Having an attribute selector for "anything with class" is not a universal thing.
    2. Even if present it would be rare. In the overwhelming majority of times one would want to use a particular class value. Just the presence or absence of the attribute is not typically worth focusing on.

    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.