PPK on JavaScript: The DOM - Part 2/Page 6
[previous] [next]
PPK on JavaScript: The DOM - Part 2
innerHTML vs. DOM
So when do you use innerHTML
, and when do you use the pure DOM? In the end, this depends on your personal coding style, and it's hard to give general rules. Nonetheless, there are some advantages to using innerHTML
for the creation of large amounts of HTML.
The power of innerHTML
lies in the ease with which you can create complicated tree structures with just one line of code. None of the example scripts contains a case in which I have to add really huge swaths of HTML to the document, so here's a contrived example of adding a slightly more complicated structure than the ones we've seen until now:
Compare this to the following script that uses pure DOM methods:
This is rather more cumbersome, especially when you want to add a static structure.
When you work with dynamic structures, however, DOM methods become more interesting. Suppose you have an array with an unknown number of message texts. All of these texts should be shown in their own <li>
s.
This is the innerHTML
version:
This is the pure DOM version:
The innerHTML version is still shorter than the pure DOM version, although the difference is not nearly as large as in the first example.
Now let's make this example a bit more complicated. There's also an array that contains the class names the <li>
s should get. With innerHTML
we get this:
For me personally, this is about the breaking point at which pure DOM methods become more attractive than innerHTML
. I find the following line becoming unreadable, and it's getting easier and easier to make mistakes in the quotes and brackets:
Some of you will have started using pure DOM methods much earlier, while others will feel innerHTML
is still the easier option. There is no simple right or wrong here; you should try to find your personal border between these two ways of working.
[previous] [next]
URL: