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/
Post a Comment