HTML and CSS Reference
In-Depth Information
and use the dataset API to modify and create our custom data, along with
setAttri
bute()
for fallback support:
<script>
var cars = document.getElementsByTagName("li");
for (var i=0; i < cars.length; i++) {
if (cars[i].dataset) {
cars[i].dataset.color = "yellow";
cars[i].dataset.rating = "awesome";
} else {
cars[i].setAttribute("data-color", "yellow");
cars[i].setAttribute("data-rating", "awesome");
}
}
var output = "What color are Kimberly's cars? ";
for (var i=0; i < cars.length; i++) {
if (cars[i].dataset) {
output += cars[i].dataset.color;
} else {
output += cars[i].getAttribute("data-color");
}
if (i != (cars.length-1)) {
output += ", "
}
}
document.getElementsByTagName("p")[0].innerHTML = output;
</script>
Discussion
Once you know how to access custom data, manipulating it is pretty easy. If you can
use the dataset API, just assign the new value to the desired attribute; otherwise, fall
back to using
setAttribute()
. This same method allows you to add new custom data
attributes, as well.
In this example, we've decided to repaint all of the cars yellow using JavaScript. Looping
through the list items, we access
dataset.color
(or use
setAttribute()
to access
data-
color
) and assign a new value of
"yellow"
.
We also use JavaScript to add a rating for each of the cars. In that same loop, we create
data-rating
by applying a value of
"awesome"
to
dataset.rating
(or use
setAttri
bute()
to do the same).
If you need to remove a custom data attribute, you can do so by setting its value to
null
. You can verify that the DOM is being manipulated by using a tool such as Opera
Dragonfly, as shown in
Figure 6-2
.
See Also