How to add content to html body using JS?

I have many <section> in my html <body> and want to add more through javascript. However, using innerHTML is just replacing my existing sections with new ones, instead of adding them to the old ones.

What else can I use?


You can use

document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)

or

document.getElementById("parentID").innerHTML+= "new content"

I Just came across to a similar to this question solution with included some performance statistics.

It seems that example below is faster:

document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');

InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.

enter image description here

Reference: 1) Performance stats 2) API - insertAdjacentHTML

I hope this will help.


I think if you want to add content directly to the body, the best way is:

document.body.innerHTML += "bla bla";

To replace it, use:

document.body.innerHTML = "bla bla";