How to add content to html body using JS?

43

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 tagged with javascript

~ Asked on 2012-11-21 14:05:08

The Best Answer is


54

You can use

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

or

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

~ Answered on 2012-11-21 14:07:26


23

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.

~ Answered on 2018-07-22 19:33:39


Most Viewed Questions: