HTML and CSS Reference
In-Depth Information
data-* (custom data attributes)
HTML5 allows custom attributes on any element. These can be
used to pass information to local scripts.
Previously, to store custom data in their markup, authors
would do something annoying like use classes: <input
class=”spaceship shields-5 lives-3 energy-75”> . Then your
script would need to waste time grabbing these class names,
such as shields-5 , splitting them at a delimiter (a hyphen in this
example) to extract the value—all very hacky and arguably an
abuse of the class attribute, which is intended (according to
HTML 4.01) as a hook for styling or for “general purpose pro-
cessing by user agents.”
In his 2007 book, ppk on JavaScript, Peter-Paul Koch explains
how to do this and why he elected to use custom attributes in
some HTML 4 pages, making the JavaScript leaner and easier to
write but also making the page technically invalid. As it's much
easier to use data-shields=5 for passing name/value pairs to
scripts, HTML5 legitimises and standardises this useful, real-
world practice and gives us a simple, standardised API to easily
access and manipulate these custom attributes.
When the data-* attributes are fully supported in a browser,
JavaScript can access the properties using
(where the data-foo attribute contains the value).
This is currently supported in all browsers except Internet
Explorer, but the polyfill at can
help with that.
Otherwise scripts can access the values via the traditional
get/setAttribute methods. The advantage of the dataset prop-
erty over setAttribute is that it can be enumerated a lot more
easily. Say, for instance, you needed to get all the values stored
in the data-* attributes; using the native functionality the code is
straightforward and as you'd expect (without any optimisation):
var values = [];
for (var key in element.dataset) {
However, to do this today, although the code has the same
result, it's not so accessible to newer developers or folk that are
less savvy with JavaScript and the DOM:
Search WWH ::

Custom Search