Search code examples
javascripthtmlclone

Clone on click does not produce new DOM element


I've got this simple JS script what I need to achieve is: every time the button is clicked a clone of the card is appended to container.

const card = document.querySelector('.card').cloneNode(true)
const button = document.querySelector('.btn')
const container = document.querySelector('.container')

button.addEventListener('click', () => {
    container.append(card)
})
<div class="container">
  <button class="btn">this is a button</button>
  <div class="card">
    <h1>This is a card</h1>
  </div>
</div>

Nothing too hard. The first time I click on button everything work fine. Why the next time the button doesn't append a new clone?


Solution

  • You are reinserting the same clone over and over again. You need to create a new clone every time the button is clicked.

    .container {
      background: #ddd;
      padding: 1em;
    }
    .card {
      display: inline-block;
      width: 5em;
      height: 10em;
      font-size: 10px;
      border: 2px solid black;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div class="container">
            <button class="btn">this is a button</button>
            <div class="card">
                <h1>This is a card</h1>
            </div>
        </div>
    
    </body>
    <script>
        const button = document.querySelector('.btn')
        const container = document.querySelector('.container')
    
        button.addEventListener('click', () => {
            const card = document.querySelector('.card').cloneNode(true)
            container.append(card);
        })
    
    </script>
    </html>