HTML data attributes are useful for passing small pieces of information to JavaScript.
For example:
<button id="save" data-enabled="false">
Save
</button>
You can read the value using dataset:
const button = document.querySelector("#save");
console.log(button.dataset.enabled);
// "false"
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");
}
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>
const cart = document.querySelector("#cart");
console.log(cart.dataset.count === 0);
// false
console.log(cart.dataset.count === "0");
// true
If you need a number, convert it:
const count = Number(cart.dataset.count);
And for a boolean, you can compare the string directly:
const isEnabled = button.dataset.enabled === "true";
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"
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)