BetterInnerHTML - an innerHTML replacement

This demonstration provides an alternative to inserting HTML into the DOM using:

  1. innerHTML - a fast but non-standard method that can be problematical, and
  2. DOM appendChild and insertBefore - safe but long-winded methods.

BetterInnerHTML allows you to specify HTML as a string (like innerHTML), but inserts elements and text using standard DOM methods. It works by loading the string as an XML document and copying it to the page.

// usage: BetterInnerHTML(element, HTML, clearfirst)
// element	- the DOM element where the HTML will be loaded
// HTML		- the string of valid HTML code
// clearfirst	- if false, existing child nodes of the element will be retained

BetterInnerHTML(document.getElementById("element"), "<p>A standard <strong>HTML</strong> string.</p>");
This text will be replaced by HTML using the BetterInnerHTML function
This text will be replaced by HTML using innerHTML.

Please view the source for the JavaScript code or download a compressed version (1KB) for use in your own code.

Refer also to this article: innerHTML: the ultimate alternative solution

You are free to use, modify, and distribute BetterInnerHTML, but please mention us and link to http://www.optimalworks.net/.

(Of course, we're happy to accept donations too!)

History

Version 1.1, 2008-01-15: fixed inline event handlers in IE, e.g. <div onclick="alert('event handler')">click me</div>. However, it is probably safer to attach events to elements after they have been added to the page - if you do that, use version 1.0 since it is marginally smaller and faster.

Version 1.0, 2007-12-19: initial release (still available for download).