In the previous section, I used the
innerHTMLis not a part of the W3C DOM specification. For some people, that's reason enough not to use it. Personally, I disagree sharply: as we'll see in this section and the next,
innerHTMLis excellently suited for some tasks, and it has perfect browser compatibility.
You'll have to decide this for yourself, but I don't see any good reasons for refusing to use
innerHTML. Instead, we should try to find out in which situations
innerHTMLwill work better than pure DOM methods, and in which situations the pure methods will have the advantage.
innerHTML gives the HTML content of an element as a string, and it also allows you to write new HTML content into an element. ake this example:
Now the alert faithfully says 'This is a <strong>bold</strong> bit of text.' You can also italicize the text:
Figure 8.13: Setting the
innerHTMLimmediately changes the document tree, too.
Garbage in, garbage out
innerHTML is so powerful, you should take care to always pass it correct HTML. Garbage HTML can cause very weird effects. Take this example:
Figure 8.14: Browsers disagree sharply on the interpretation of the malformed HTML.
The browsers must solve the problem of the missing
</strong> tag somehow. Each finds its own solution, and likely none of these solutions are what you want. Obviously, you should avoid this by making sure you always pass correct HTML to the
innerHTML is noticeably faster than pure DOM methods in the current browsers. When you append one or two children to an element, the speed difference isn't really important; the user hardly distinguishes between, say, a 7- and a 12-millisecond delay. However, once you start creating complicated structures such as tables, using
innerHTML instead of
appendChild() is a noticeable improvement.
The speed difference between
innerHTML and pure DOM methods goes from three times as fast (Mozilla, Opera) to thirty times as fast (Explorer).
innerHTMLis faster? Because I tested it. See http://www.quirksmode.org/dom/innerhtml.html for the test page.