The HTML5 spec define how to set custom attributes using data-* prefix, like:
<div data-attr="somedata"></div>
But what would be the difference if we write just:
<div attr="somedata"></div>
And I actually prefer the second way since it's shorter.
I can access both attributes using the getAttribute()
method.
So is that wrong not using data-* prefix? I tested it only on chrome and IE11, so maybe there are other browsers to worry about?
HTML5 defines the data-*
attributes as valid, while other custom attributes are not. So what?
If you run your code through an HTML validator it will look for invalid attributes. Among other things, they could indicate a typo. An HTML5 validator will accept data-*
attributes but it isn’t psychic. It has no way of judging which other new attributes are part of the plan.
If you create a new attribute, it may not play nicely with future changes in HTML which may coincidentally use the same attribute name for a different purpose. The data-*
attributes are exempt from future implementation.
A corollary of the above is that including additional libraries which also make arbitrary changes may interfere with your own code.
JavaScript cooperates with the data-*
attributes by automatically collecting them in a dataset
property for each element. If you make up another attribute it won’t be included.
If none of the above points are important to you, then, by all means, use whatever attribute names you like. As regards the last point above, you can always access your own arbitrary attributes using JavaScript’s *Attribute
functions which will work just well on any attribute, regardless of its validity.
Speaking of JavaScript, there is no concept of HTML validity for JavaScript, and you can use JavaScript to assign any attribute names you like without fear of the HTML validator police knocking at your door. However, you still run the risk of competing with additional libraries or future implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With