Custom data attributes (data-*) can be used to store extra information for an HTML element. Although you can read and write these data-attributes using attribute methods (getAttribute(), setAttribute() etc), but there is an alternate way to do so using the dataset property of the element.
The dataset property allows access only to data-attributes. No other attributes of the element can be accessed.
<div id="container" data-type="post" data-post-id="123">Post 1</div>
var element = document.querySelector("#container");
// accessing data-type="post"
console.log(element.dataset.type);
// accessing data-post-id
console.log(element.dataset.postId);
The data attributes defined in HTML need to be converted to camel case convention before using them in Javascript.
Naming Convention
In HTML markup, data-attributes are specified in a dash-style (data-post-id). This needs to be converted to a camelCase format to access those attributes through dataset. The rules for this conversion are :
- the prefix data- is removed.
- for any other dashes that are followed by a lowercase letter (a-z) : The dash is removed and the character that follow the dash is converted to uppercase.
- other characters are not changed.
Giving a few examples :
- data-post is converted to post
- data-post-id is converted to postId
- data-post-name-format is converted to postNameFormat
- data-post--count is converted to post-Count
Reading a Data-Attribute
The value of the data-attribute can be read from the element's dataset property using the camelCase converted name as the key.
var element = document.querySelector("#container");
// accessing "data-type"
console.log(element.dataset.type);
// accessing "data-post-id"
console.log(element.dataset.postId);
Values can be read as bracket-syntax also :
console.log(element.dataset['type']);
console.log(element.dataset['postId']);
Changing Value of Data-Attribute
// changing "data-type"
element.dataset.type = 'picture';
// changing "data-post-id"
element.dataset.postId = 150;
// changing "data-type"
element.dataset['type'] = 'picture';
// changing "data-post-id"
element.dataset['postId'] = 150;
This can also be used to create a new data-attribute, if it does not exist previously.
Checking whether Data-Attribute Exists
The in operator can be used to check whether the data-attribute is existing or not.
// true or false
console.log('postId' in element.dataset);
It will give a boolean true if the attribute exists, and false otherwise.
Deleting a Data-Attribute
The delete operator can be used to delete a data-attribute.
delete element.dataset.postId;