I have some javascript that looks like this:
var sel = '<option value="{value}" {selected}>{name}</option>';
...
$(index + '_expiry').innerHTML = sel; // $(index + '_expiry) is a select.
This works fine in firefox, but not in Internet Explorer – not even IE9.
There is already a solution to this problem that involves creating new elements in the DOM rather than changing the innerHTML.
Is it wrong to insert new elements into a page by manipulating .innerHTML? I use the innerHTML approach all over my site and it is easy. It works in IE for simple elements like .div too.
Though IE is often annoying to work with, the newer versions have a stricter javascript parser that is probably more correct – for instance, it doesn’t like an array created as ['a','b','c',].
So, is it bad, inefficient, unreliable, or similar to use .innerHTML to create new HTML elements in the DOM? Should I use it for only inserting plain text? Or is this just IE benig stubborn?
Subjective
Usually more efficient then the alternatives in terms of run time. The cost comes from making sure the strings are properly constructed.
Browsers are consistent (although not always with other browsers), so you can rely on decently tested code.
IE doesn’t like editing the insides of certain elements (tables and select elements in particular).