Get and Set Data Attributes with JavaScript

β€” 4 minute read


Did you ever use some weird class like class="user-fuu" for JavaScript to then pick up this class?

Since the HTML5 specification, we can use something better for this, and it's called data attributes!

Let's dive into data attributes and get an HTML element with them.

HTML Markup permalink

<div id="demo" data-user="fuu" data-custom-emoji="πŸ”₯"></div>

This is a very simple example. For each element we want to add, we can use a data attribute data- with a name. Note we use multiple dashes instead of spaces.

Vanilla JS get element with the dataset API permalink

So HTML5 brings us the wonderful Dataset API, much like the classList, as we explored before. But it's not quite as impressive.

We can use it to get and set data attributes.

Getting a Data Attribute permalink

To get the value from a data attribute in JavaScript we can use the following code:

const element = document.getElementById('demo');


// fuu
// πŸ”₯

Pretty cool right!

Note that, to get the data from the attribute we have to use camelCase writing in our code for the attributes with multiple dashes. That's the rule.

Setting Data Attributes permalink

To set the value of data attribute, we use the same dataset API again:

element.dataset.customEmoji = '⚑️'; = 'Fuu?';

// ⚑️
// Fuu?

As you can see, we can easily overwrite data attributes and even add new values!

Magic powers and trust me, you will use this quite often.

Alternative method setAttribute and getAttribute permalink

An alternative is using setAttribute and getAttribute methods in JavaScript.

element.setAttribute('data-custom-emoji', '🀟');
// 🀟

As you can see, this method needs the dash-style again.

Using Data Attributes in CSS permalink

Another strong value for data attributes is that they can be accessed in CSS!

Look at this example:

[data-user] {
width: 50px;
height: 50px;
background: teal;
border-radius: 50%;

Wow, what can these bad boy data attributes not do right!

See the JavaScript code examples in this Codepen permalink

See the Pen Vanilla JS Data Attributes set and get by Chris Bongers (@rebelchris) on CodePen.

Browser support permalink

Really good browser support for dataset, so why not use it!

browser support for data attributes

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter