Skip to main content

Laconic: a New Way to Generate DOM Content from JavaScript


Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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:

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 created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.