Why should I prepend my custom attributes with "data-"?
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?)
There are several benefit for keeping custom attributes prefixed with data-*.
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 oninput
elements is known to have had some clashes on some popular websites in the past)There is a convenient DOM API, HTMLElement.dataset, for accessing these attributes from scripts. It is now supported in most browsers.
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.
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.