In this blog post we will learn about the custom data-* attributes introduced in html and manipulate it in javascript.
HTML elements comes with predefined attributes like “id, name, class”. In some scenarios we need a way to pass an extra data through a custom attribute that is not included in the HTML element specification just to solve specific problem.
For this web browsers introduced a new attribute “data-*“. I intended to use this attribute a lot specially when dealing with libraries such as Jquery to query and manipulate the DOM.
“data-” attributes can be declared on any element by passing “data-<attribute name>” for example:
<button data-userid="2" data-username="john doe" data-email="user@info.com">Click here</button>
By using the data- attributes allows to pass any number of custom attributes.
Manipulation With Javascript
To access data- attributes with javascript there are many ways:
- Using dataset property:
The javascript dataset property return a DOMStringMap of all the “data-” attributes defined on element if any.
<button data-userid="2" data-username="john doe" data-email="user@info.com" onclick="handleclick(this)">Click here</button> <script> function handleclick(element) { console.log(element.dataset); } </script>
// console output
DOMStringMap {userid: '2', username: 'john doe', email: 'user@info.com'}
So we can easily access any attribute using attribute name after the “-” like so:
const userid = element.dataset.userid; const username = element.dataset.username; const email = element.dataset.email; console.log(userid, username, email);
The dataset property not only allows to read values but also to set values:
const btn = document.querySelector("button"); btn.dataset.userid="44";
To remove a data- attribute using dataset property we can use the delete operator:
delete btn.dataset.email;
- Using getAttribute():
This is usual way to read any attribute by giving the full attribute name:
const userid = element.getAttribute('data-userid'); const username = element.getAttribute('data-username'); const email = element.getAttribute('data-email');
Using data-* With Jquery
The jquery includes the .data() function which allows to set or get a data- attribute:
var userid = $("span").data( "userid" );
For storing data- attribute provide a second argument to .data():
$("span").data( "userid", "2" );