[javascript] 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?

This question is related to javascript

The answer is


You're probably using

document.getElementById('element').innerHTML = "New content"

Try this instead:

document.getElementById('element').innerHTML += "New content"

Or, preferably, use DOM Manipulation:

document.getElementById('element').appendChild(document.createElement("div"))

Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.


Try the following syntax:

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

Working demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>

</body>
</html>

In most browsers, you can use a javascript variable instead of using document.getElementById. Say your html body content is like this:

<section id="mySection"> Hello </section>

Then you can just refer to mySection as a variable in javascript:

mySection.innerText += ', world'
// same as: document.getElementById('mySection').innerText += ', world'

See this snippet:

_x000D_
_x000D_
mySection.innerText += ', world!'
_x000D_
<section id="mySection"> Hello </section>
_x000D_
_x000D_
_x000D_


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

It seems that example below is faster:

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

InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.

enter image description here

Reference: 1) Performance stats 2) API - insertAdjacentHTML

I hope this will help.


Just:

    document.getElementById('myDiv').innerHTMl += "New Content";

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

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

To replace it, use:

document.body.innerHTML = "bla bla";