user14800938
user14800938

Reputation:

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?

Upvotes: 0

Views: 49

Answers (2)

Zoli Szab&#243;
Zoli Szab&#243;

Reputation: 4534

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>

Upvotes: 1

trincot
trincot

Reputation: 350270

You only made one single clone before the click happened. You should make a new clone on each click.

So move the assignment to card inside the click handler:

const button = document.querySelector('.btn');
const container = document.querySelector('.container');

button.addEventListener('click', () => {
    const card = document.querySelector('.card').cloneNode(true);
    container.append(card);
});

Unrelated, but please terminate your statements with ;. You don't want to rely on the automatic semicolon insertion mechanics, which can sometimes have surprising effects.

Upvotes: 1

Related Questions