简体   繁体   中英

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?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM