Carlos Gil
Carlos Gil

Reputation: 605

Using custom attributes in DOM elements, with boolean value

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

Upvotes: 2

Views: 2850

Answers (1)

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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!

Upvotes: 3

Related Questions