HTML and CSS Reference
In-Depth Information
6.4 Accessing Custom Data with JavaScript
You want to access the custom data in your page and execute some logic based on the
Start with the same markup as that in Recipe 6.3 , but add a paragraph for JavaScript
<h1>My Volkswagens</h1>
<li data-year="1996" data-color="white" data-engine="VR6">Cabrio</li>
<li data-year="1993" data-color="purple" data-engine="VR6">Corrado</li>
<li data-year="2008" data-color="red" data-engine="2.0T">Eos</li>
<li data-year="2003" data-color="blue" data-engine="W8">Passat</li>
Access the custom data using the dataset API:
var cars = document.getElementsByTagName("li");
var output = "What color are Kimberly's cars? ";
for (var i=0; i < cars.length; i++) {
output += cars[i]. dataset .color;
if (i != (cars.length-1)) {
output += ", "
document.getElementsByTagName("p")[0].innerHTML = output;
With the introduction of custom data attributes, HTML5 also defines the dataset DOM
API. This is a simple and easy way of accessing any custom data associated with any
The JavaScript is straightforward: we create an array of all list items ( cars ), and we
create a string that is inserted into the paragraph ( output ). As we iterate over the cars
array, we use dataset.color to access the value of each data-color attribute and append
it to the output variable. The end result is the phrase “What color are Kimberly's cars?
White, purple, red, blue” being added to the paragraph at the end of the list.
Not all browsers yet support the dataset API (see Table 6-1 ), but accessing custom
data attributes in all browsers is easy. Where dataset is not supported, simply use
Search WWH ::

Custom Search