I have many in my html
and want to add more through javascript. However, using
innerHTML
is just replacin
You can use
document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)
or
document.getElementById("parentID").innerHTML+= "new content"
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>
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";
Try the following syntax:
document.body.innerHTML += "<p>My new content</p>";
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.
Reference: 1) Performance stats 2) API - insertAdjacentHTML
I hope this will help.
Just:
document.getElementById('myDiv').innerHTMl += "New Content";