Javascript:DIV AppendChild
Asked Answered
E

2

11

In the below code "objTo" is a div to which i need to insert multiple number of div. when i use the code for the first time its working.but on the next time its overwriting the existing code.

     <script>

var divtest= document.createElement("div");        
divtest.innerHTML = "<div>new div</div>"         
objTo.appendChild(divtest)
    </script>

Where am i going wrong?

Estelaestele answered 26/4, 2012 at 6:21 Comment(1)
Running that code multiple times won't overwrite anything (other then a reference that you no longer need). I suspect you have created a reduced test case that has reduced away the problem.Samford
E
34

I have made a very simple working version for you :

http://jsfiddle.net/hQKy9/

Multiple clicks works the whole time :

Script

function addDiv() {
    var objTo = document.getElementById('container');
    var divtest = document.createElement("div");
    divtest.innerHTML = "new div";
    objTo.appendChild(divtest);
}

Html

<div id="container"></div>

<input type="button" onclick="addDiv();" value="Click here to add div"/>
Exchange answered 26/4, 2012 at 6:35 Comment(0)
E
0

Even through Marc gave the ans before I found it we can do more like adding ID/Class and CSS like the following way I did

const newChild = document.createElement('div');
newChild.id = 'newly_content';
newChild.innerHTML = `
    <p style="font-size: 30px;padding: 200px 0px 10px 0px;">
        A new content has been created!
    </p>
`;
document.getElementById('ItemID').appendChild(newChild);
Eogene answered 2/6, 2022 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.