Boolean data-* Attributes

html, javascript

Solution

You can indeed use `data-*` attributes as if they were boolean attributes - however, as far as `dataset` is concerned `<input data-on>` is equivalent of `<input data-on="">`. This means that unlike `required` or other boolean attributes you won't be able to do this:

<input class="some-class" data-on required>

var elementOfInterest = document.querySelector(".some-class");
if (elementOfInterest.dataset.on) {
    // We will never get here because dataset.on === ""
    // and "" == false
}

if (elementOfInterest.required) {
    // We *do* get here because required is a boolean attribute
}

Instead you'll need to do an explicit check against undefined:

if (elementOfInterest.dataset.on !== undefined) {
    // We will get here because "" !== undefined
}

This gives you no way of distinguishing between `data-on` and `data-on=""`, but if you are treating it as a boolean attribute, they both add up to the same thing anyway (only the absence of the attribute indicates falsity.)

Problem

Can you use `data-*` attributes as boolean attributes? If not, is there an alternative? For example, you can have ``` <input disabled> ``` It would be helpful in some cases to have ``` <input data-on> ``` Using `data-on="true"` or `data-on=""` is not desirable -- the presence of the attribute should indicate its boolean value.

Original source

Related problems