I want to copy the div element and paste it next to it when a button is clicked.
Here is my attempt which doesn’t work.
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>
<div style="width: 18rem;" class="card" id="box">
<div class="card-body">
<h5 class="card-title" id="Cat1"></h5>
<p class="card-text">No Products Created</p>
<a href="#" class="btn btn-primary">+</a>
</div>
</div>
<button onclick="addItem()">Click Me!</button>
<script>
function addItem() {
let input = document.createElement('div');
input.id("box");
document.getElementById("box").appendChild(input);
}
</script>
</body>
</html>
2
Answers
Here is the solution.
.createElement
will create a new element and you can’t use the id because id is unique and can be used once in a page. You can use class for replication.You can use the
cloneNode()
method to clone the element, and then use theappendChild()
method to put the cloned element anywhere.Just note that the
cloneNode()
method may lead to duplicate IDs. You should handle that, citing from MDN: