59

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?

1
  • 4
    If you provide your code so far, you'll get a more specific answer. Commented Nov 21, 2012 at 14:06

11 Answers 11

68

You can use

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

or

document.getElementById("parentID").innerHTML+= "new content"
Sign up to request clarification or add additional context in comments.

3 Comments

I'd always go for DOM methods where possible; .createElement, .appendChild, .insertBefore, .replaceChild, etc.
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 :)
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.
34

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.

2 Comments

Thanks! insertAdjacentHTML method is quite helpful!
Also good to mention that it works on most of the browsers including Internet Explorer 4+
28

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

5 Comments

To append instead of erase >> document.body.innerHTML += "bla bla";
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.
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
This answer is breaking so many things as @LukasLiesis has pointed. No idea why so many upvotes...
@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.
14

Try the following syntax:

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

4 Comments

For those coming to this question via Google etc: This answers the question in the title. +1
Readers should also check out the excellent shortcut in the answer by Ulysse BN, below.
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.
this brakes modern JS apps. use dom API appendChild or similar
6

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.

7 Comments

Please don't suggest w3schools to people, it is not officially related to w3 and has a lot of misinformation (see w3fools.com )
@PaulS. If you have a different DOM manipulation tutorial for me, I'll gladly change the link.
I had to search for some and found these; Navigating the DOM, Modifying the DOM. True, they're not "easy reads" yet but it is a wiki in it's alpha stages.
@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 man, there is no innerHtml property. Please, update your answer with the correct syntax - innerHTML.
|
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>

Comments

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>

Comments

1

you can also do like this

document.querySelector("#yourid").append('<div>my element<div>');

Comments

1
document.querySelector('body').appendChild( //your content )

Comments

0

Just:

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

2 Comments

hmm that will append then new html code not replace it
so I think the answer it's right but not explain at all
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.