Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery’s answer below for details.

For older browsers, and node/jsdom: (which doesn’t yet support <template> elements at the time of writing), use the following method. It’s the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

Note that unlike HTML templates this won’t work for some elements that cannot legally be children of a <div>, such as <td>s.

If you’re already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

  • Prototype has this feature built-into its update() method.
  • jQuery has it implemented in its jQuery(html) and jQuery.parseHTML methods.

Leave a Comment