DEV Community

Chris Bongers
Chris Bongers

Posted on • Originally published at on

Vanilla JavaScript Data Attributes

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

Since HTML5 Spec, we can use something better for this, and it's called Data Attributes!

Let's dive into using Data Attributes together.

HTML Markup

<div id="demo" data-user="fuu" data-custom-emoji="🔥"></div>
Enter fullscreen mode Exit fullscreen mode

Very simple, for each element we want to add, we can use data- with a name, note we use multiple dashes for spaces.

Vanilla JavaScript dataset API

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 only get and set data.

Getting a Data Attribute

To get a data attribute we can use the following code:

var element = document.getElementById('demo');console.log(element.dataset.user);console.log(element.dataset.customEmoji);// fuu// 🔥
Enter fullscreen mode Exit fullscreen mode

Pretty cool right!

Note that we have to use camelCase to retrieve the data, while we inputted as dash-style. This is the rule, and we have to obey to it.

Setting Data Attributes

To set, we use the same Dataset API

element.dataset.customEmoji = '⚡️'; = 'Fuu?';console.log(element.dataset.customEmoji);console.log(;// ⚡️// Fuu?
Enter fullscreen mode Exit fullscreen mode

As you can see, we can easily overwrite data attributes, or even add new ones!

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

Alternative method setAttribute and getAttribute

An alternative is using setAttribute and getAttribute methods.

element.setAttribute('data-custom-emoji', '🤟');console.log(element.getAttribute('data-custom-emoji'));// 🤟
Enter fullscreen mode Exit fullscreen mode

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

Using Data Attributes in CSS

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%;}
Enter fullscreen mode Exit fullscreen mode

Wow, what can these bad boy Data Attributes not do right!

See the following Codepen for all these examples:

See the Pen Vanilla JavaScript Data Attributes by Chris Bongers (@rebelchris) on CodePen.

Browser support

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

Dataset browser support

Thank you for reading, and let's connect!

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

Top comments (0)