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/bootstrap@5.3.0/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>
>Solution :
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.
function addItem() {
const node = document.querySelector(".card-body");
const clone = node.cloneNode(true);
document.getElementById("box").appendChild(clone);
}
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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>
</body>
</html>