Monday, February 26, 2007

How to parse HTML strings into DOM nodes without innerHTML

Here's a way of parsing a string of HTML into a series of DOM nodes in Firefox and other Mozilla-similar ("mozimilar") browsers:

var range = document.createRange();
range.selectNode(document.body);
var parsedHTML = range.createContextualFragment(SomeStringOfHTML);

document.body.appendChild(parsedHTML)

The call to selectNode() is required as you have to point the empty range at something before you can use it; Firefox throws an exception without it. You can use other range positioning methods as well.

Also of note: createContextualFragment() is not part of any DOM specification AFAICT, so you should feel appropriately shameful about using it as you would innerHTML.