[whatwg] boolean attributes in javascript

On Tue, 8 Dec 2009, Brian Kuhn wrote:
>
> How do I correctly set a boolean attribute on a DOM element object in 
> Javascript?

Content attribute or IDL attribute?

> var script = document.createElement('script');
> 
> script.async = true;

For IDL attributes, this is the way to do it.


> To me, boolean attributes seem to break the rule of least
> surprise<http://en.wikipedia.org/wiki/Principle_of_least_astonishment>.
>  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>

That's just how HTML has always been, I think it's a lost cause to try to 
change direction now. We'd just end up confusing people more.

Note that the best way to write it is just:

   <script async src="..."></script>

...which seems clear to me.


On Tue, 8 Dec 2009, Brian Kuhn wrote:
> 
> I understand that if it's present, it's on.  So, why can't async="true" 
> be valid?  I think all browser vendors will implement it that way 
> anyway.  They'd be crazy not to.

On Tue, 8 Dec 2009, Tab Atkins Jr. wrote:
> 
> Indeed, async="true" does set it to be on.  However, so does 
> async="false", async="off", async="no", and any other string you can 
> think of that might imply that it's turned off.  Setting it to *any* 
> value turns it on, so it's best to avoid values that would lead to 
> confusing results.  The two values that are currently valid are the 
> minimum necessary, and neither have antonyms that would confuse people.

As Tab says, allowing "true" would imply "false" had the opposite meaning, 
which it doesn't. This would lead to even more confusion.


On Tue, 8 Dec 2009, Brian Kuhn wrote:
>
> I can accept that.  It's just a shame that true and false can't be 
> supported for something called a boolean attribute.

Agreed.


> Anyone have any thoughts on setAttribute vs. setting the attribute 
> directly?  My test show that they both work.

With .setAttribute() you have to do:

   script.setAttribute('async', '');

...or:

   script.setAttribute('async', 'async');

...and indeed, these and setting .async both work.


On Wed, 9 Dec 2009, Markus Ernst wrote:
> 
> HTML:
> <input type="checkbox" name="box1">
> <input type="checkbox" name="box2" checked>
> (or: checked="checked", or checked="")
> 
> Javascript:
> document.forms[0].elements["box1"].checked = false;
> document.forms[0].elements["box2"].checked = true;

Correct.

-- 
Ian Hickson               U+1047E                )\._.,--....,'``.    fL
http://ln.hixie.ch/       U+263A                /,   _.. \   _\  ;`._ ,.
Things that are impossible just take longer.   `._.-(,_..'--(,_..'`-.;.'

Received on Wednesday, 24 March 2010 02:03:47 UTC