Question about appendChild

Hello,

I have a hard time figuring out how to use appendChild().

Basically, what I do now is:

myDiv.innerHTML += someHtml;

But instead, I would like to do:

myDiv.appendChild(someHtml);

where myDiv is an element targeted with getElementById and someHtml, well, some html (paragraphs wrapped in a div).

So far, I can’t get appendChild() to work…

Anyone can give me some advice?

:slight_smile:

appendChild works with elements, not text, even if that text represents HTML.


p.appendChild(document.createTextNode('This is an example of some '));
strong.appendChild(document.createTextNode('strongly marked'));
p.appendChild(strong);
p.appendChild(document.createTextNode(' and some '));
em.appendChild(document.createTextNode('emphasised'));
p.appendChild(em);
p.appendChild(document.createTextNode(' text.'));

For example, as a test page:


<html>
<head>
    <title>An appendChild example</title>
</head>
<body>
<div id="content"></div>
<script>
var p, strong, em, div;

p = document.createElement('p');
strong = document.createElement('strong');
em = document.createElement('em');

p.appendChild(document.createTextNode('This is an example of some '));
strong.appendChild(document.createTextNode('strongly marked'));
p.appendChild(strong);
p.appendChild(document.createTextNode(' and some '));
em.appendChild(document.createTextNode('emphasised'));
p.appendChild(em);
p.appendChild(document.createTextNode(' text.'));

div = document.getElementById('content');
div.appendChild(p);
</script>
</body>
</html>