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:
,
, or
.
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
should equal
). You can use the above code for more general string testing by removing != null && a !== false
.