Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to clone an element and create it everytime a button is clicked

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading