11 May 2008

Why I hate innerHTML

Why I hate innerHTML? Because IE suck! It doesn't work for select tag in IE. I have something like

<select id="foo"><option value="1">baz</option></select>

Javascript that doesn't work in IE:
document.getElementById("foo").innerHTML = '<option value="2">baz</option>';

Solution -- have to use DOM lah! Note that use innerHTML will destroy the tag events. My prefered solution:

document.getElementById("foo").options[0] = new Option("baz", 2);

Astute reader may ask, why not use dom method add() ? Again, because IE suck!

var x=document.getElementById("foo");
x.add(y,null); // standards compliant
x.add(y); // IE only


More love/hate on innerHTMl, http://www.wait-till-i.com/2006/04/18/innerhtml-vs-dom-pot-noodles-vs-real-cooking/


Abdullah Zainul Abidin said...

Why not just use an established js library like mootools or prototype? Much easier and they're tested on most browsers.

mr fakap said...

bloated probably?

Max said...

@abdullah zainul abidin: Using a library may help, but you need to know if the library has a hack to fix this bug (and the 100's of others) out there.

The Select innerHTML bug (#274) is documented / tracked here:

And here is a few more related IE Select issues.




It would be nice to see a comparison of libraries to see which ones handle the major IE bugs.

Anonymous said...

instead of declaring index manually, you can simply use add() to populate the selection box

x.options.add(new Option(...));

where x is a selection box element

Anonymous said...
This comment has been removed by a blog administrator.