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

JavascriptHtmlDom

Javascript Problem Overview


I need to be able to add elements to a page given a raw text string of HTML, including any number of tags, attributes etc. Ideally I would like to be able to do something like with any arbitrary string of well-formed html;

 var theElement = document.createElement("<h1 id='title'>Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>");

document.getElementById("body").appendChild(theElement);

Obviously that doesn't work, I'm looking for good ways to achieve the same result. I'd like to avoid parsing the HTML if possible. I'm severely restricted on the tools I can use, no jQuery or outside includes and must be cross-browser and backward compatible down to IE6. Any help would be huge.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

You can use insertAdjacentHTML:

document.body.insertAdjacentHTML("beforeend", theHTMLToInsert);

There are options other than beforeend, but it sounds like you want to append to the element, which is what beforeend does.

Live Example:

document.body.insertAdjacentHTML("beforeend", "<div>This is the new content.</div>");

<div>Existing content in <code>body</code>.</div>

Unlike using += with innerHTML, this doesn't require the browser to spin through the content of the element and create an HTML string to represent it, destroy those elements (including any event handlers they have on them), and replace them with the same elements plus your additions. It just adds your additions, leaving the existing content unchanged.

Solution 3 - Javascript

var el =  document.createElement("h1")
el.id="title";
el.innerHTML = "Some title";
document.body.appendChild(el);

var el2 =  document.createElement("span")
el2.style.display="block";
el2.style.width="100%";
el2.innerHTML = "Some arb text";
document.body.appendChild(el2);

Shoud work (fiddle: http://jsfiddle.net/gWHVy/)

edit: This is a solution for the special case that you know the properties of direct children of what you want to insert. Take a look at the solution of Aaron that works in the general case.

Solution 4 - Javascript

You could get the elementId of the element under which you wish to insert the HTML and use innerHTML for adding the html.

document.getElementById("body").innerHTML = "<h1 id='title'>Some Title</h1><span>test</span>";

Solution 5 - Javascript

maerics solution fixed my problem straight away. I however needed to make a quick tweak to it to do what I needed. I have several scripts and stylesheets that load on click. I can't add either scripts or stylesheets as actual objects to the DOM post-load. If you set innerHTML for say, document.body, to contain the <link rel="stylesheet" /> part, it will only print the text and the browser will not recognize it as a link object. To fix this, I used the following code.

function appendHtml(el, str) {
  var div = document.createElement('div');
  div.innerHTML = str;
  while (div.children.length > 0) {
      if ( div.children[0].tagName == 'LINK' ) {
          // Create an actual link element to append later
          style = document.createElement('link');
          style.href = div.children[0].href;
          // append your other things like rel, type, etc
          el.appendChild(style);
      }
      el.appendChild(div.children[0]);
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkirpsView Question on Stackoverflow
Solution 1 - JavascriptmaericsView Answer on Stackoverflow
Solution 2 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 3 - JavascriptbeardhatcodeView Answer on Stackoverflow
Solution 4 - JavascriptVivek ViswanathanView Answer on Stackoverflow
Solution 5 - JavascriptAaronView Answer on Stackoverflow