MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

HTML5 Custom Data Attribute

Xah Lee,

Discovered custom data attribute in HTML5. Basically, you can have arbitrary attribute names, and the only requirement is that the names starts with data-. Here's a example used by twitter:

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

Here's the spec: Source dev.w3.org. Quote:

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 characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).

Using JavaScript to Access Custom Data Attribute

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

Why's This Useful?

Here's a example of how i use it.

I write many blogs, often i link to other sites. I want the link to contain accessed date, so if years later the link went dead, i know the date i viewed it, and can then possibly dig it up.

Because there isn't a attribute for access date, and i don't want access date as text because that's distracting to readers. So, i use the “title” tag as a workaround, like this:

<a href="…" title="accessed:2012-09-22">important article</a>

Now i change them to this:

<a href="…" data-accessed="2012-09-22">important article</a>

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

〈Google Custom Search Element〉 @ <s class="deadurl" title="accessed:2009-06-11; defunct:2012-07-06">http://www.google.com/webelements/customsearch/</s>

Now i can do it like this:

〈Google Custom Search Element〉 @ <s class="deadurl" data-accessed=":2009-06-11" data-defunct="2012-07-06">http://www.google.com/webelements/customsearch/</s>
blog comments powered by Disqus