Skip to content Skip to sidebar Skip to footer

Do Html5 Data Attributes Need A Value?

I am wondering if html data attributes actually need a value to be applied? I wonder this because often all we want to know is if the attribute is actually set to act as a flag. (s

Solution 1:

No. But...

As is common with all attributes, in the application/xhtml+xml serialisation, XML rules apply and the attribute must have an explicit name and (quoted) value.

So this question is really about the text/html serialisation, and therefore the relevant part of the HTML5 spec is Section 8 The HTML syntax

In particular, under attributes, it says:

Attributes can be specified in four different ways:

where the first of these is:

Empty attribute syntax

   Just the attribute name. The value is implicitly the empty string.

It's necessary to understand though that the value is of string type, not of boolean type.

For example, with <input id="cb" type="checkbox" checked>, the "checked" attribute is reflected by a property that is either true or false. So

if (document.getElementById("cb").checked)

will evaluate to true for the above markup.

In contrast, with <input id="cb" type="checkbox" data-checked>, the "data-checked" attribute is reflected via the dataset object as a string. The value of this property is the empty string, which in JavaScript is falsey. So,

if (document.getElementById("cb").dataset.checked)

will evaluate to false for the above markup.

To do the equivalent test, compare the value for "not undefined". I.e.

if (document.getElementById("cb").dataset.checked !== undefined)

will evaluate to true for the above markup.

See http://jsfiddle.net/GAxvW/


Solution 2:

Simple Boolean Test For Element Attributes

To expand on Alohci's excellent answer, the following is a simple, flexible way to test for a true boolean attribute value supplied using one of three standard HTML conventions: <foo data-bar/>, <foo data-bar="true"/>, or <foo data-bar="data-bar"/>.

var a = elem['data-bar'];
var aTrue = ( a != null && a !== false && a !== 0 && a.charAt(0) != 'f' &&
              a.charAt(0) != 'n' );

With the code above, the value is false if undefined or set to one of: f*, n*, 0 (case-insensitive), and true if defined and set to one of: (empty string), (attribute name), (anything else).

Empty strings are evaluated to true here because HTML attributes without values are '' which equal false in JS (and something like <foo disabled/> should equal <foo disabled="true"/>). You can use the above code for more general string testing by removing != null && a !== false.


Post a Comment for "Do Html5 Data Attributes Need A Value?"