Reputation: 69
**I have seen similar questions but they haven't provided me a close solution.
Add the new div <div class="container" id="section"style="border: 1px solid grey;">
and all the tables and fields hold with this div
on a button click.
I'm trying to append it by following code.
function run() {
var div = document.createElement("div"); //create new div
div.addEventListener("click", run); //bind click to new div
this.appendChild(div); //append the new div to clicked div
this.removeEventListener("click", run); //remove the original click event
}
document.getElementById("section").addEventListener("click", run);
Can anyone please help me to sort this out. Thank you in advance.
Upvotes: 0
Views: 15858
Reputation: 317
If I understand you correctly, you want to clone an entire section (including its children) on a button click and append that below the original.
You can do that with cloneNode(true)
- but be aware that it will copy any field names (such as those on inputs).
container.appendChild(sourceNode.cloneNode(true))
document.getElementById("newsectionbtn").onclick = function() {
var container = document.getElementById("container");
var section = document.getElementById("mainsection");
container.appendChild(section.cloneNode(true));
}
section { border:1px solid #ddd; }
<div id="container">
<button id="newsectionbtn">+New Section</button>
<section id="mainsection">
<table>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="f1" /></td>
<td><input type="text" name="f2" /></td>
</tr>
</tbody>
</table>
</section>
</div>
Upvotes: 3
Reputation: 407
click inside red square)
function run() {
var div = document.createElement("div"); //create new div
div.addEventListener("click", run); //bind click to new div
this.append(div); //append the new div to clicked div
this.removeEventListener("click", run); //remove the original click event
}
document.getElementById("section").addEventListener("click", run);
div{
border: 4px solid red;
padding: 4px;
}
<button id="section">run</button>
Upvotes: 1