HTML and CSS Reference
In-Depth Information
6.4 Accessing Custom Data with JavaScript
Problem
You want to access the custom data in your page and execute some logic based on the
data.
Solution
Start with the same markup as that in Recipe 6.3 , but add a paragraph for JavaScript
output:
<h1>My Volkswagens</h1>
<ul>
<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>
</ul>
<p></p>
Access the custom data using the dataset API:
<script>
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;
</script>
Discussion
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
element.
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