51

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?

kenorb
  • 155,785
  • 88
  • 678
  • 743
apr
  • 527
  • 1
  • 4
  • 7

11 Answers11

60

You can use

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

or

document.getElementById("parentID").innerHTML+= "new content"
Amberlamps
  • 39,180
  • 5
  • 43
  • 53
Sajjan Sarkar
  • 3,900
  • 5
  • 40
  • 51
  • 6
    I'd always go for DOM methods where possible; [`.createElement`](https://developer.mozilla.org/en-US/docs/DOM/document.createElement), [`.appendChild`](https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild), [`.insertBefore`](https://developer.mozilla.org/en-US/docs/DOM/Node.insertBefore), [`.replaceChild`](https://developer.mozilla.org/en-US/docs/DOM/Node.replaceChild), etc. – Paul S. Nov 21 '12 at 14:13
  • 13
    I know this is an old answer, but += on innerHTML is a not a good way of appending content to an element. I did the += on an element that had ads loaded already and the ads actually just went blank after appending content. Switching to appendChild(element) vs += "content" fixed the ad disappearing issue. Just an FYI for future users who landed on this page from Google :) – Joe Oct 17 '13 at 20:43
  • 2nd brakes modern JS apps and many other things, especially ones working with "virtual" DOM aka ReactJs and similar. Use appendChild always. 2nd option will take current value, append your new string, and replace the current value, which terminates connection between virtual dom state and dom rendered on screen. stuff will brake. use use 1st. `appendChild` or other DOM api. – Lukas Liesis Aug 13 '20 at 11:11
28

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.

speksy
  • 700
  • 8
  • 13
26

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";
Community
  • 1
  • 1
Webbing
  • 293
  • 3
  • 2
  • 6
    To append instead of erase >> document.body.innerHTML += "bla bla"; – Trev14 Apr 20 '17 at 23:06
  • 1
    This answer is misleading, because the first way (`document.body.innerHTML = "bla blah";`) is not adding content to the body, it's ***replacing*** the content in the body. And the user specifically asked for a way to add content to a body that already has existing content. So the answer to the question is what you're showing as technique #2. Technique #1 you could add as a side note with explanation. – jbyrd Dec 27 '18 at 19:59
  • 1
    this has side effects on JS apps and this approach brakes events and all kind of random things. Do not "add" to innerHTML. Use DOM API e.g. `appendChild` – Lukas Liesis Aug 12 '20 at 08:19
  • This answer is breaking so many things as @LukasLiesis has pointed. No idea why so many upvotes... – Peska Mar 30 '23 at 18:51
  • @Peska it has upvotes because it provides feel of working. You can run this code and it will do the thing. If app would have nothing more, it would be perfectly fine but usually apps have a bit more than such line, then stuff will break and it will be terrible day finding out why completely "unrelated" thing breaks your code. It's like AI generated code, often works w/o any clue of how wrong it is. – Lukas Liesis Apr 01 '23 at 13:18
14

Try the following syntax:

document.body.innerHTML += "<p>My new content</p>";
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • 4
    **For those coming to this question via Google etc:** This answers the question in the title. +1 – cssyphus Jun 08 '18 at 04:12
  • Readers should also check out the excellent shortcut [in the answer by Ulysse BN](https://stackoverflow.com/a/45488487/1447509), below. – cssyphus Mar 21 '19 at 23:12
  • This does a replace + append, not just an append. On a long page, this could be very slow and one might see a page flash. – Volomike Apr 01 '19 at 15:54
  • this brakes modern JS apps. use dom API `appendChild` or similar – Lukas Liesis Aug 13 '20 at 11:09
5

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.

JakeParis
  • 11,056
  • 3
  • 42
  • 65
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Please don't suggest w3schools to people, it is not officially related to w3 and has a lot of misinformation (see http://w3fools.com ) – Paul S. Nov 21 '12 at 14:15
  • @PaulS. If you have a different DOM manipulation tutorial for me, I'll gladly change the link. – Cerbrus Nov 21 '12 at 14:18
  • I had to search for some and found these; [Navigating the DOM](http://docs.webplatform.org/wiki/tutorials/traversing_the_dom), [Modifying the DOM](http://docs.webplatform.org/wiki/tutorials/creating_and_modifying_html#Creating_HTML). True, they're not "easy reads" yet but it is a wiki in it's alpha stages. – Paul S. Nov 21 '12 at 14:39
  • @PaulS. Thanks, I'll add them in. I've just read through the page you linked... There's some pretty darn stupid mistakes around w3schools o.O – Cerbrus Nov 21 '12 at 14:55
  • @Cerbrus man, there is no `innerHtml` property. Please, update your answer with the correct syntax - `innerHTML`. – likerRr Aug 03 '17 at 10:52
  • @likerRr: It looks like you found a _very_ old answer of mine... Wow, I had much to learn back then o.O – Cerbrus Aug 03 '17 at 11:00
  • So, @likerRr, care to remove the DV now? – Cerbrus Aug 03 '17 at 12:38
3

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>
Saravanan Nandhan
  • 579
  • 10
  • 19
2

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:

mySection.innerText += ', world!'
<section id="mySection"> Hello </section>
Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
1

you can also do like this

document.querySelector("#yourid").append('<div>my element<div>');
Andrew Nic
  • 108
  • 1
  • 11
1
document.querySelector('body').appendChild( //your content )
ians19
  • 11
  • 2
0

Just:

    document.getElementById('myDiv').innerHTMl += "New Content";
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
0

recently, I faced the same issue but I wanted to add content just at the beginning of the content of the body. so I found this solution worthy: using insertAdjecentHTML(positions, text) while specifying the position. The position can either 'beforebegin', 'afterbegin', 'beforeend', 'afterend'

const element = document.getElementById('my-id')

element.insertAdjacentHTML(position, text);
giles
  • 85
  • 1
  • 9