Came across the most frustrating IE bug (for IE 7 anyway, there are rumours that this has been fixed in IE8, though I haven’t dared to try yet.
let’s set it up: you have an existing <FORM> element somewhere on your page, and for whatever reason you would like to add elements (such as a hidden field, or a textbox) to this form dynamically from a JavaScript function.
(Sane) Non-IE code:
newField = document.createElement("input");
newField.setAttribute("name", "myNewField");
newField.setAttribute("type", "hidden");
newField.setAttribute("value", "it is a secret");
theForm = document.getElementById("myForm");
theForm.appendChild(newField);
Loverly! A little wordy and all that, but hey, that’s what working (correctly) with the DOM is like, and we get used to it. Though we never love it (that’s where MooTools etc come in…)
Of course, if we do a little peeking around with
alert(theForm.innerHTML);
Everything is beautiful in the “good” browsers (FF and Chrome et al) and then we look at IE. Guess what?
Internet Explorer does not allow you to set the name attribute of an element after it’s been created. Yep. It’s a read-only property. element.setAttribute(“name”, “whatever”) fails. silently.
In some peabrained propellerhead way, I can see that this makes sense – IE used to use “name” the way the DOM uses ID, and changing something’s ID after it’s created can cause havoc. If you’re a lazy-ass, short-sighted programmer of course.
But we already knew that that’s a primary job qualification of the IE development team, right?
Enough griping, Tom you ass, what’s the workaround?
IE has this really ugly (mis)implementation of document.createElement() that fails in all other browsers, where you can actually pass the entire HTML element as a string. Not just the node name (ie: “input”) but the actual HTML (ie: “<input name=’blah’>”).
This is the ONLY time you can set the name attribute – on creating the element.
But I mentioned that it fails (errors out) in other browsers.
So, we wrap the whole ugly baby in a swaddling try…catch statement and send it down the river like so….
Ugly-ass Try…Catch Wrapper for Uglier-Ass IE Element Creation Code
try {
// for IE, curse it
newField = document.createElement("<input name='uglyBaby'>");
} catch (error) {
// for all other sane browsers that bothered to read the DOM specification
newField = document.createElement("input");
newField.setAttribute("name", "happyChild");
}
// ... and then you can set all your other attributes nicely here for all browsers...
I need to go puke somewhere. Please excuse me.
