Ever need to create a <button>
of type button
when you’re doing a little DOM scripting? Easy enough, right? It should go something like this:
var okButton = document.createElement('button');
okButton.type = 'button';
Nevertheless when you run this code in IE6, you get the super-informative “Communication error” message. It turns out that IE6 (for once) is following the standard. I don’t know what the W3C were thinking, but so sayeth the ECMAScript Language Binding (9 January 2003) spec about the type
property of the HTMLButtonElement
:
- type
- This read-only property is a String.
So, the common way to set the property of an HTML element is, according to the standard, right out? I mean, it’s not inconceivable that I would want to create a <button>
on the fly with a type that is not the default.
Alas there is a workaround. Ironically, it employs the standard method of setting DOM Node
‘s attribute value:
var okButton = document.createElement('button');
okButton.setAttribute('type', 'button');
Works like a charm! Even in IE6.
(I should note that Firefox 3 allows for writing to the button’s type property using the button.type
notation. I didn’t test with other browsers to see whether they balk at the button.type
notation, but Firefox 2/3, Opera 9.6, and Safari 3, along with IE6/7, are more than amenable to the setAttribute
method.)