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.
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.
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.