BetterInnerHTML - an alternative to innerHTML
BetterInnerHTML provides an alternative way of inserting HTML into the DOM. Normally, developers would either use:
- innerHTML - a fast but non-standard method that can produce problems, or
- DOM appendChild and insertBefore - a safer method, but it results in long-winded code.
BetterInnerHTML allows you to specify HTML as a string (like innerHTML), but inserts elements and text using standard DOM methods. It works by parsing the string as XML and copying all nodes and attributes to the page.
BetterInnerHTML works in all major browsers including Internet Explorer, Firefox, Opera, Safari and Chrome.
BetterInnerHTML demonstration
Example code
// 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>");
Note that the HTML string must be valid XHTML. Closing tags must be used, e.g. an image tag needs a closing slash: <img src="image.jpg" />
Download BetterInnerHTML
Please view the source of this page for the JavaScript code or download a compressed version of BetterInnerHTML for use in your own code (1KB)
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/.
Please make a donation to support further development of BetterInnerHTML
Please contact Optimalworks if you would like to sponsor this page with your own advertisement.
History
Version 1.2, 2009-07-21: multiple inline event handlers are now supported.
Version 1.15, 2008-05-14: fixed a minor bug that prevented strings of 2 characters being rendered. (The fix has also been applied to version 1.0).
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 safer to attach events to elements after they have been added to the page.
Version 1.0, 2007-12-19: initial release (if you do not use inline event handlers, the shorter and faster v1.0 is still available for download).
Known issues
HTML entities such as © or » will not work when passed in the HTML string. It is possible to fix this issue, but it adds a significant amount of code.