InnerHTML vs. DOM Manipulation Part 2 (IE9 Edition)

A while ago I researched some of the differences in modifying the structure of an HTML document using innerHTML or the DOM. The summary at that time was that, while using innerHTML means less code, most modern browsers provide negligible differences in execution time. That is, of course, provided you minimize modifications to the active document (web page) directly, as each will potentially cause a redraw operation. The bottom line was that it was personal preference, with a tradeoff on less code or more standards-adherence and reliability.

There is an epilogue to this story:

My personal preference is to using standards for cross-browser reliability. Unless file size is a concern (low-bandwidth networks) or large scale input modifications are needed (re-creating large portions of a document programmatically), working with the DOM directly is easier in the long run. It seems the output of innerHTML can vary across browsers, depending on the node structure underneath. This can make comparing DOM structure (unit tests, for example) by innerHTML difficult to get right cross-browser. Where as most browsers will concatenate nodes together without a space (<div><span></span></div>), IE seems to in some/most instances use spaces between nodes on output: (<div> <span> </span> </div>).

While this may seem an edge case, it’s one more argument to be mindful of using DOM-standard tools and apis.

Comments

2 responses to “InnerHTML vs. DOM Manipulation Part 2 (IE9 Edition)”

  1. Jared - Regina Web Design Avatar

    Are there any real world, modern, specific examples why you should NOT use innerHTML?

    1. sweerdenburg Avatar

      Well, the biggest argument against it is that it’s non-standard, so even if it exists cross-browser, quirks may come up (like the spacing issue above). A few notes from the MSDN page:

      “By definition, elements that do not have both an opening and closing tag cannot have an innerHTML property.”
      While some elements require distinct open and close tags to function (like a script tag), others, like div tags, can be processed even if it’s not valid to self-close the tag (

      ). Not having a standard definition of behaviours leads browser vendors to interpret their own “best” way to handle these cases.

      There are also some elements it is read-only on, and modifications must be done through the standard DOM:
      “The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.”

Leave a Reply

Discover more from Software by Steven

Subscribe now to keep reading and get access to the full archive.

Continue reading