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