[whatwg] boolean attributes in javascript

Tab Atkins Jr. jackalmage at gmail.com
Tue Dec 8 13:41:42 PST 2009


On Tue, Dec 8, 2009 at 1:49 PM, Brian Kuhn <bnkuhn at gmail.com> wrote:
> How do I correctly set a boolean attribute on a DOM element object in
> Javascript?
> var script = document.createElement('script');
>
> script.async = true;        // makes the most sense, but appears go against
> the spec
> script.async = 'true';       // worse, but not bad, but also appears to go
> against the spec
> script.async = '';            // sets to empty string, but what does that
> really mean?
> script.async = 'async';   // sets async = async, which is weird and verbose
>
> And then you have the debate on setting the property directly versus using
> setAttribute.  Any thoughts on that?
>
> To me, boolean attributes seem to break the rule of least surprise.  I find
> it very hard to believe people will understand:
> <script async="" src="..."></script>    or   <script async="async"
> src="..."></script>
> more than:
> <script async="true" src="..."></script>

Setting an attribute foo to '' or 'foo' is the correct way.  To unset
it, remove the attribute entirely.

This is mostly unchangeable now, because it's how HTML and XHTML have
worked for a long time.  XHTML requires the longer foo="foo" form, and
in HTML writing an element like <bar foo> will give the element an
attribute "foo" with the value of the empty string.  Thus those are
the two proper ways to set it.  For compatibility reasons setting
*any* value on the attribute sets it (it's set or not based purely on
the presence or absence of the attribute itself, not the value of the
attribute), but it's invalid to set it to anything other than the two
values I just mentioned.

If authors are writing HTML, they can just do <script async src="…">.
Simple and easy.

~TJ



More information about the whatwg mailing list