Question

So any custom data attribute that I use should start with "data-":

<li class="user" data-name="John Resig" data-city="Boston"
     data-lang="js" data-food="Bacon">
  <b>John says:</b> <span>Hello, how are you?</span>
</li>

Will anything bad happen if I just ignore this? I.e.:

<li class="user" name="John Resig" city="Boston"
     lang="js" food="Bacon">
  <b>John says:</b> <span>Hello, how are you?</span>
</li>

I guess one bad thing is that my custom attributes could conflict with HTML attributes with special meanings (e.g., name), but aside from this, is there a problem with just writing "example_text" instead of "data-example_text"? (It won't validate, but who cares?)

Was it helpful?

Solution

There are several benefit for keeping custom attributes prefixed with data-*.

  1. It guarantees there will not be any clashes with extensions to HTML in future editions. This is a problem that has been encountered to some degree already with some of the new attributes introduced in HTML5, where existing sites were using attributes with the same name and expecting different and incompatible, custom behaviour. (e.g. the required attribute on input elements is known to have had some clashes on some popular websites in the past)

  2. There is a convenient DOM API, HTMLElement.dataset, for accessing these attributes from scripts. It is now supported in most browsers.

  3. They provide a clear indication of which attributes are custom attributes, and which ones are standardised attributes. This not only helps validators by allowing them to permit any attribute with data-* while still performing useful error checking for other attributes (e.g. to catch typos), it also helps make this aspect of the source code clearer to those reading it, including people who may work on a website after the original author.

OTHER TIPS

According to John Resig, the whole purpose of the addition of these custom data attributes to the HTML5 sepcs is to allow to embed custom data in HTML while still being valid.

If you don't care about validation (and, as you said, your custom attributes are not colliding with existing HTML attributes like name, id, style, etc.), then I guess you don't have to use the data- prefix. But considering that this is not a huge cost for writing valid, compatible code, I don't see why you wouldn't do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top