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.
The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .
Create a dummy element and assign it to a variable. We can extract later using the element objects. Assign the HTML text to innerHTML of the dummy element and we will get the plain text from the text element objects.
createElement Function in JavaScript. The createElement() function in JavaScript is used to programatically add elements to the DOM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With