Convert HTML string to element

E

eggie5

I want to use element.appendChild(child) on a string of HTML I have:

html=

'<div>
<strong>Text</strong>
</div>'

However, since it's not an element (ie created with
document.createElement) I can't use appendChild with my html string.
The only way I know to get it in the document is to use
element.innerHTML, however I want to use appendChild. So my question
is, how can I convert my HTML string into an element object that I can
use with appendChild()?
 
R

RobG

I want to use element.appendChild(child) on a string of HTML I have:

html=

'<div>
<strong>Text</strong>
</div>'

However, since it's not an element (ie created with
document.createElement) I can't use appendChild with my html string.
The only way I know to get it in the document is to use
element.innerHTML, however I want to use appendChild. So my question
is, how can I convert my HTML string into an element object that I can
use with appendChild()?

Use createElement('div') and insert the string using innerHTML. Then
cycle through the div's child nodes and insert them where you wish.

<script type="text/javascript">

function insertHTML (el, htmlString) {
var p = el.parentNode;
var d = document.createElement('div');
d.innerHTML = htmlString;
for (var i=d.childNodes.length; i; i) {
p.insertBefore(d.childNodes[--i], el.nextSibling);
}
}

</script>
<button onclick="
var s = '<p>Here is a paragraph with <span style=\'color:red;\'>'
+ 'some red <b>text</b></span></p>'
+ '<p>Another paragraph</p>';
insertHTML(document.getElementById('xx'), s);
">Insert stuff</button>
<div id="xx"></div>

If you intend inserting into tables, you'll need something a bit
smarter.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,260
Latest member
kentcasinohelpWilhemina

Latest Threads

Top