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.)