The HTML5 DOM Element API: Dataset18 Oct 2011
Using data attributes on elements
Datasets are added to an element via element attributes. A dataset attribute is prefixed by
data- and followed by the name. For example,
For this post, we are going to use a photo gallery as an example of when you might want to use datasets to add additional markup to your HTML. To start, let us create the first
div with attributes that define the author, location, and date of the photo. Here is the markup:
As you can see, the three items we want in the dataset are prefixed by
data- and are assigned a value the same way as any other HTML attribute.
Accessing an element’s dataset
To access the dataset of an element, simply use the attribute
dataset. Here is a quick example.
Modifying and removing an element’s dataset
Modifying an item in the dataset is very easy, just assign the property in the dataset a new value.
Deleting is equally easy, just use the keyword
delete and specify the property of the dataset to delete.
Using data attributes with CSS
Like other HTML Element attributes, dataset attributes can be used as part of CSS selectors. Adding a blue background to all divs with Dave as the author looks like the following: