views:

62

answers:

1

Is there a way to add attributes to a DOM element with boolean value like this:

<body test='false'></body>

I need to set this without using javascript.

Thanks

+1  A: 

HTML5 has something called data-attributes that might fit your needs. You could do something like this:

<body data-test="true"></body>

And then check the boolean value of the attribute like this (using jQuery):

!!$('body').attr('data-test')

Explanation of the "double bang" operator:

You can get the boolean value of any javascript object like this:

!!0 //false

!!1 //true

!!undefined //false

!!true //true

Edit

As noted by David, a non-empty string (like "false" for example) would yield true.

You've got 2 options here:

  • dont set the attribute, which will be undefined and hence false

  • compare to the string "true" instead of using the !! operator

Hope that helps!

Pablo Fernandez
… but the string `"false"` is `true`
David Dorward
That is quite a big edit … which doesn't address the problem `!!"false" // true`
David Dorward
@David fixed now
Pablo Fernandez