Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 447
kirps Avatar asked Apr 25 '12 05:04

kirps


People also ask

Can I add HTML as innerHTML?

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

How do I make HTML text Plain?

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.

Does document createElement add to DOM?

createElement Function in JavaScript. The createElement() function in JavaScript is used to programatically add elements to the DOM.


2 Answers

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. 
like image 132
maerics Avatar answered Oct 04 '22 00:10

maerics


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.

like image 27
T.J. Crowder Avatar answered Oct 03 '22 22:10

T.J. Crowder