HTML and CSS Reference
In-Depth Information
Custom data
The data-* attribute is a bit of an odd one. It is the catchall of attributes, allowing any
attribute name to be added for the purposes of storing custom data in HTML elements
for the use of, for instance, JavaScript applications. The * in the attribute name is not the
actual finished attribute; it can be replaced with any text to create custom attributes. For
example, city could be added to create the attribute data-city . Or score could be
added to create data-score , which might be used on a web page listing high scores
for a game. Take the following HTML snippet, for instance:
<button id="show-score-button">Show Scores</button>
<ul>
<li data-score="3200">Top Blaster Tom</li>
<li data-score="2250">Middle Range Merv</li>
<li data-score="1100">Last Pop Louis</li>
</ul>
A JavaScript function could then be written that replaces the user name with the win-
ning score when clicking a button:
function showScore(){
document.getElementById("show-score-button").onclick =
function(){
var entries = document.getElementsByTagName("li");
entries[0].innerHTML
=
entries[0].dataset["score"];
entries[1].innerHTML
=
entries[1].dataset["score"];
entries[2].innerHTML
=
entries[2].dataset["score"];
}
}
window.onload = showScore;
Note The dataset property in the previous code allows access to data-* attrib-
utes as key/value pairs. However, only the custom part of the attribute is needed, so the
attribute score is looked up in the dataset, not data-score .
This permits a lot of flexibility in what can be stored in an individual element but at
the same time is backed by a specific specification. How paradoxical! The intention is
that these attributes are used only within a particular site, and they are not utilized by
Search WWH ::




Custom Search