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.
Here is a little code that is useful.
--Convert the HTML string into a DOM Element
--prototype helper
--Usage
Just give an
id
to the element and process it normally eg:Now you can do like:
Or with jQuery:
You can use a
DOMParser
, like so:Okay, I realized the answer myself, after I had to think about other people's answers. :P
You can do it like this:
Why not use insertAdjacentHTML
for example: