Search code examples
htmlweb-componentcustom-data-attributelit-element

Can non data- attributes on custom elements become standard attributes?


In this article the author suggests using data- attributes in the design of a syntax highlighting web component.

The reason given is:

Technically speaking, the browser would let us write the attributes like this:

<code-tab language="HTML" escaped="true" line-numbers="true">

But if any of those attribute names ever become web standard, that could cause issues. Data attributes protect us from that, as they're developer defined.

Is this correct?

Can attributes themselves become a web standard? I assumed their meaning would be based on the context, so an attribute like language within a code-tab context would treated as being unique to that context?


Solution

  • Yes it's entirely correct, as an example, recently the HTML standards did add a popover attribute to all elements. If your custom element was using that attribute, then it would now be rendered with a default display: none rule1:

    if (!("popover" in HTMLElement.prototype)) {
      console.warn("This browser doesn't support the popover attribute");
    }
    <my-elem>Some content</my-elem>
    <my-elem popover>Hey!?</my-elem>

    Better use data-attribute indeed.
    It might also be considered relatively safe to use attributes that are already defined on other elements, and which would thus not make it as global attributes since there would be a clash. But even then be careful, because in some cases some attributes could apply on custom elements too. For instance, form-associated custom-elements will have a default reaction for the form, disabled, readonly, and name attributes. While this require an opt-in and is thus less likely to cause an issue, we don't know what the future is made of.
    But obviously, you can discard these recommendations and use whatever works, until it doesn't...


    1. Or if your component had enough popularity, it could prevent the standards from using a perfectly fitting attribute name because it would break the websites using it.