HTML5 Custom Data Attribute

, , …,

HTML5 has a “custom data attribute”. It lets you to have any attribute/value pairs in a tag. Such attribute has names starting with data-. Here's a example used by Twitter:

<a href="" class="twitter-share-button" data-via="xah_lee">Tweet</a>

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters.

Why's This Useful?

Here's one example of using it as accessed date of a site.

<a href="…" data-accessed="2012-09-22">7 Tips You Must Know</a>

When the site went dead, you can add a defunct date, like this:

<a href="…" data-accessed="2012-09-22" data-defunct="2012-07-06">7 Tips You Must Know</a>

You can use it for any purpose you want for your website or online app.

Using JavaScript to Access Custom Data Attribute

You can use JavaScript/DOM's “getAttribute” method, like any other attribute. See: JavaScript: Get Element's Attribute Value.

Like what you read? Please tell friends, share link, or Buy JavaScript in Depth. Thanks.
blog comments powered by Disqus