Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)

Try assigning to the innerHTML property of an anonymous element and appending each of its children.

function appendHtml(el, str) {
  var div = document.createElement('div');
  div.innerHTML = str;
  while (div.children.length > 0) {
    el.appendChild(div.children[0]);
  }
}
var html="<h1 id="title">Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>";
appendHtml(document.body, html); // "body" has two more children - h1 and span.

Leave a Comment