Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)
dom, html, javascript
Solution
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.
Problem
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.