How to add content to html body using JS?

Try the following syntax:

document.body.innerHTML += "<p>My new content</p>";

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";

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.

Tags:

Javascript