innerHTML: the ultimate alternative solution
written by craig, 19 December 2007
It’s incredibly useful and very fast, but it comes with some baggage:
- invalid HTML can be inserted, making errors difficult to spot and debug
- if you want to do anything complex, innerHTML will cause problems. In particular, you may not be able to examine nodes in the resulting DOM, event handlers can be removed, some elements are not supported, and browser issues will occur.
- it’s not a part of the W3C standard. Yet. Although most browsers support innerHTML, it just feels … a little dirty.
The alternatives until now
The main alternative is to manually update the DOM using appendChild or insertBefore. It works, but it’s no fun, requires a lot of code, and is impractical for larger chunks of HTML.
I’ve seen some great ideas that use JSON-like structures or create functions for every HTML tag. It’s clever and significantly reduces the coding effort – but they’re not as easy as innerHTML.
BetterInnerHTML: the ultimate solution!
It works by loading the HTML string as an XML document, then recursing the nodes and copying each one into the DOM. The function takes the following arguments:
BetterInnerHTML(element, HTMLstring, clearfirst);
- element is a DOM node
- HTMLstring is the HTML you want to insert, and
- clearfirst is an optional argument – set it to false to keep the existing child nodes and append the new HTML below them
"<p>A standard <strong>HTML</strong> string.</p>"
- it’s as easy to use as innerHTML but doesn’t have the problems
- unlike innerHTML, you do not need to destroy the existing content (set clearfirst to false).
- it’s less than 50 lines of code – just an additional 1KB to your script library
- it works in every mainstream browser (IE, Firefox, Opera and Safari) in HTML or XHTML pages
- if you’re retrieving XML content via Ajax requests, there’s no need to create a new XML document – the script can be modified accordingly.
The potential pitfalls:
- it’s slower than innerHTML for large strings or frequent inserts – but that isn’t typical in a well-devised web system
- strictly speaking, XML manipulation methods aren’t part of the W3C standards. However, like XmlHttpRequest, they are supported by most browsers and BetterInnerHTML safely updates the DOM using the XML as a reference only.
- it’s impossible to test all combinations of OS and browser, so let me know if you find any problems.
I still have a nagging doubt that this solution is too simple and too easy! Please leave your comments…