2

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

10
  • What do you mean? It is a boolean value. Do you mean 1 or 0? Then, you'll need to change how you write it. How do you write it? Commented Aug 15, 2010 at 8:32
  • No there isn't. Attributes are always strings in HTML. Depending on what you are going to do with this attribute you might need to parse it. Also notice that according to the w3c spec there's no test attribute defined on the body tag meaning that your HTML is not valid. Commented Aug 15, 2010 at 8:35
  • 2
    The fact that something is a valid boolean is only relevant in the context of a programming language. If you are not using javascript... where do you need to retrieve the value as a boolean? (and why did you tag this question with javascript in the first place) Commented Aug 15, 2010 at 8:38
  • 1
    @Darin: What you should say is that his HTML won't validate under a given schema. It's valid HTML, and indeed the approach of custom attributes is widely used. Commented Aug 15, 2010 at 8:38
  • 4
    @silky: No, it’s not valid HTML. It is valid SGML but it’s not valid HTML. Commented Aug 15, 2010 at 8:41

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

2 Comments

… but the string "false" is true
That is quite a big edit … which doesn't address the problem !!"false" // true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.