🤯 50% Off! 700+ courses, assessments, and books

Laconic: a New Way to Generate DOM Content from JavaScript

Craig Buckler
Share

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");
newstrong.appendChild(document.createTextNode("DOM"));
newpara.appendChild(document.createTextNode("Here's some new "));
newpara.appendChild(newstrong);
newpara.appendChild(document.createTextNode(" content."));

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

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.


$.el.p(
	"Here's some new ",
	$.el.strong("DOM"),
	" content."
).appendTo(document.getElementById("container"));

Attributes are supported using object literal notation:


// produce <div class="example"><div>Content</div></div>
$.el.div(
	{ "class": "example"},
	$.el.div("Content")
);

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: