Content can be inserted into your page using innerHTML or outerHTML…

var container = document.getElementById("container");
container.innerHTML = "<p>Here's some new <strong>DOM</strong> content.</p>";

(Note that jQuery also uses innerHTML for DOM content manipulation).

It’s fast and easy — but it’s not without problems:

  1. Invalid HTML strings can be inserted which make errors difficult to spot and debug.
  2. You may encounter browser issues if you attempt complex activities such as using or modifying nodes in the resulting DOM content.
  3. Although it’s well supported, innerHTML is a proprietary technology and not part of the W3C DOM. It offends the standards gods.

So let’s look at the DOM-based alternative:

var newpara = document.createElement("p");
var newstrong = document.createElement("strong");
newpara.appendChild(document.createTextNode("Here's some new "));
newpara.appendChild(document.createTextNode(" content."));

var container = document.getElementById("container");

Nasty. It’s three times longer, slower to execute and still prone to human error.

Several years ago I devised by own solution, BetterInnerHTML, which loaded an HTML string as XML, recursed the structure and inserted appropriate nodes into the DOM. It worked, but I was never totally happy with performance or issues such as HTML entities.

Fortunately, Joe Stelmach has devised an alternative. It’s a small standalone utility named Laconic which uses a logical JavaScript notation to map directly to HTML, e.g.

	"Here's some new ",
	" content."

Attributes are supported using object literal notation:

// produce <div class="example"><div>Content</div></div>
	{ "class": "example"},

I like it. While innerHTML remains the best option for quick and dirty DOM content generation, Laconic will be useful in those odd situations when it fails to work as expected.

For more information and downloads, refer to:

Tags: DOM, javascript, jQuery Tutorials & Articles
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.