This question already has an answer here:
Is there a way to convert HTML like:
<div>
<a href="#"></a>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you,
innerHTML
is exactly what you want. From this SO question:You typically create a temporary parent element to which you can write the
innerHTML
, then extract the contents:If the element whose outer-HTML you've got is a simple
<div>
as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a<li>
, you'd have to have the parent wrapper be a<ul>
.But IE can't write
innerHTML
on elements like<tr>
so if you had a<td>
you'd have to wrap the whole HTML string in<table><tbody><tr>
...</tr></tbody></table>
, write that toinnerHTML
and extricate the actual<td>
you wanted from a couple of levels down.