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

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


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");
try
{
x.add(y,null); // standards compliant
}
catch(ex)
{
x.add(y); // IE only
}

http://www.w3schools.com/htmldom/met_select_add.asp

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

5 comments:

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:
http://webbugtrack.blogspot.com/2007/08/bug-274-dom-methods-on-select-lists.html

And here is a few more related IE Select issues.

http://webbugtrack.blogspot.com/2007/09/bug-116-for-attribute-woes-in-ie6.html

http://webbugtrack.blogspot.com/2007/11/bug-291-no-styling-options-in-ie.html

http://webbugtrack.blogspot.com/2007/11/bug-293-cant-disable-options-in-ie.html

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.