PPK on JavaScript: The DOM - Part 2/Page 4 | WebReference

PPK on JavaScript: The DOM - Part 2/Page 4


[previous] [next]

PPK on JavaScript: The DOM - Part 2

F: innerHTML

In the previous section, I used the innerHTML property for certain jobs, but it's time to discuss it more formally. Even though officially it's a Microsoft proprietary property, it is supported by all modern browsers, and is a required item in the bag of tricks any JavaScripter should carry.

innerHTML and the Specs: innerHTML is 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, innerHTML is 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 innerHTML will 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



Figure 8.13: Setting the innerHTML immediately changes the document tree, too.


Garbage in, garbage out

Since 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
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 property.

Speed

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 createElement()/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).

Speed Tests: How do I know innerHTML is faster? Because I tested it. See https://www.quirksmode.org/dom/innerhtml.html for the test page.


[previous] [next]

URL: