6

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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Essentially `data-on` is `data-on=""`, using jQuery you can simply do `$("input").is("[data-on]");` – FabianCook Aug 02 '13 at 00:41
  • note: var t=document.createElement("input"); t.disabled=true; t.outerHTML == ''; so i would say no, but you can serialize the HTML differently than the browser... – dandavis Aug 02 '13 at 00:42
  • The *presence* of the attribute should indicate its boolean value: `typeof element.dataset.on !== 'undefined'`. – dfsq Aug 02 '13 at 00:51

2 Answers2

7

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

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
1

Yes, data-* attributes can function as boolean attributes, at least as far as the DOM and browser selector engines are concerned: http://jsfiddle.net/MhJNb/

I haven't tested compatibility, but Chrome has no problem with applying div[data-on] rules to <div data-on></div>.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139