DEV Community

Soren Sterling
Soren Sterling

Posted on

A small thing about HTML data attributes

HTML data attributes are useful for passing small pieces of information to JavaScript.

For example:

<button id="save" data-enabled="false">
  Save
</button>
Enter fullscreen mode Exit fullscreen mode

You can read the value using dataset:

const button = document.querySelector("#save");

console.log(button.dataset.enabled);
// "false"
Enter fullscreen mode Exit fullscreen mode

The interesting part is that the value is a string, not a boolean.

So this doesn't work as you might expect:

if (button.dataset.enabled) {
  console.log("Button is enabled");
}
Enter fullscreen mode Exit fullscreen mode

The message will still be logged.

That's because "false" is a non-empty string, and non-empty strings are truthy in JavaScript.

The same thing happens with numbers.

<div id="cart" data-count="0"></div>
Enter fullscreen mode Exit fullscreen mode
const cart = document.querySelector("#cart");

console.log(cart.dataset.count === 0);
// false

console.log(cart.dataset.count === "0");
// true
Enter fullscreen mode Exit fullscreen mode

If you need a number, convert it:

const count = Number(cart.dataset.count);
Enter fullscreen mode Exit fullscreen mode

And for a boolean, you can compare the string directly:

const isEnabled = button.dataset.enabled === "true";
Enter fullscreen mode Exit fullscreen mode

One other detail: even if you assign a boolean through JavaScript, it gets converted to a string.

button.dataset.enabled = false;

console.log(button.dataset.enabled);
// "false"

console.log(typeof button.dataset.enabled);
// "string"
Enter fullscreen mode Exit fullscreen mode

It's not a big issue once you know about it, but it can be confusing when a condition seems to ignore a false value.

I usually just make the conversion explicit when reading from dataset.

Top comments (0)