Search code examples
htmlcustom-data-attribute

Is there any reason I should stick strictly to "data-" attributes for custom attributes?


Like the title says, is there any reason I can't create arbitrary names for my own attributes?


Solution

  • Yes.

    MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

    1. Clean "namespace": You don't need to restrict yourself about which attributes you can use. data-bgcolor is safe to use, bgcolor is not.

    2. Semantics: The way data and non-data attributes are accessed is different. Usually, attributes will be retrieved using el.getAttribute("value"), while data attributes will be access with el.dataset.value. This is no confusion about what the attribute does (is it visual or not).

    3. It's standard: HTML5 declares a specific set of valid attributes. Going against standards should generally be avoided.