Learn About HTML data-* attributes

Learn About HTML data- attributes

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:

     data-username="john doe"
     data-email="">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="" onclick="handleclick(this)">Click here</button>

        function handleclick(element)

// console output

DOMStringMap {userid: '2', username: 'john doe', email: ''}

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 =;

console.log(userid, username, email);

The dataset property not only allows to read values but also to set values:

const btn = document.querySelector("button");

To remove a data- attribute using dataset property we can use the delete operator:



  • 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" );



0 0 votes
Article Rating

What's your reaction?

Not Sure

You may also like

Notify of
Inline Feedbacks
View all comments