Vanilla JavaScript Data Attributes

— 4 minute read

permalink

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 permalink

<div id="demo" data-user="fuu" data-custom-emoji="🔥"></div>

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

Getting a Data Attribute permalink

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
// 🔥

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 permalink

To set, we use the same Dataset API

element.dataset.customEmoji = '⚡️';
element.dataset.bar = 'Fuu?';
console.log(element.dataset.customEmoji);
console.log(element.dataset.bar);

// ⚡️
// Fuu?

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 permalink

An alternative is using setAttribute and getAttribute methods.

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

As you can see, this method needs to 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 following Codepen for all these examples:

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

Browser support permalink

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

Dataset browser support

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