[whatwg] boolean attributes in javascript

Thomas Broyer t.broyer at gmail.com
Tue Dec 8 15:27:34 PST 2009


On Tue, Dec 8, 2009 at 8: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

The WebIDL snippet in [1] defines the property as being of type
'boolean', and WebIDL defines how it is to be bound in ECMAScript [2],
which in turn defers to ECMAScript for the ToBoolean conversion [3]
(§9.2 in both ES3 and ES5, which have identical behavior)
So you'd do script.async=true.
script.async = 'true' would also work, but script.async = 'false'
would actually set it to true, as well as script.async = 'async'.
script.async = '' would set it to false.

[1] http://dev.w3.org/html5/spec/Overview.html#script ("DOM interface")
[2] http://dev.w3.org/2006/webapi/WebIDL/#es-boolean
[3] http://www.ecma-international.org/memento/TC39-M.htm

> And then you have the debate on setting the property directly versus using
> setAttribute.  Any thoughts on that?

Use properties, it's so easier!

> 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>

Most people would simply srite <script src="..." async></script>

Boolean attributes work that way since very early versions of HTML,
because of a feature of SGML that allows the value to be omitted when
it's the same as the attribute name (I'm not an SGML expert, someone
correct me if I'm wrong; what I'm saying is that it's the way to go in
SGML):
   <input disabled>
   <input readonly>
   <img ismap>
   etc.

-- 
Thomas Broyer
/tɔ.ma.bʁwa.je/



More information about the whatwg mailing list