471,086 Members | 811 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,086 software developers and data experts.

Convert HTML string to element

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

Mar 12 '07 #1
1 10458
On Mar 12, 4:52 pm, "egg...@gmail.com" <egg...@gmail.comwrote:
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.
--
Rob
Mar 12 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Fu Bo Xia | last post: by
5 posts views Thread by jk | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.