Tomas Am
Tomas Am

Reputation: 503

After first append javascript is not adding a cloned item for the second time

In my application I am adding cloned elements:

        document.getElementById("add").addEventListener("click", function(){
            let theblock = document.getElementById("theblock").cloneNode(true);
            let newer = theblock;
            newer.removeAttribute("id");
            document.getElementById("restblocks").append(newer);

Bit if I do cloning outside scope it adds the element to html only once:

        let theblock = document.getElementById("theblock").cloneNode(true);
        document.getElementById("add").addEventListener("click", function(){
            let newer = theblock;
            newer.removeAttribute("id");
            document.getElementById("restblocks").append(newer);

What could be the reason?

Upvotes: 1

Views: 46

Answers (1)

pilchard
pilchard

Reputation: 12928

Because when you clone outside you only ever make a single clone, and a Node can only exist in one place in a document. If you want to avoid the query inside the click handler you can query outside, but clone inside.

let theblock = document.getElementById("theblock");

document.getElementById("add").addEventListener("click", function(){ 
  let newer = theblock.cloneNode(true);
  ...
});

const theblock = document.getElementById('theblock');
const restblocks = document.getElementById('restblocks');

document.getElementById('add').addEventListener('click', function () {
  let newer = theblock.cloneNode(true);

  newer.removeAttribute('id');
  newer.classList.remove('hidden');

  restblocks.append(newer);
});
.block { width: 40px; height: 40px; margin: 4px; background-color: pink; }
.hidden { display: none; }
<button type="button" id="add">Add a block</button>
<div id="restblocks"></div>

<div id="theblock" class="block hidden"></div>

Upvotes: 2

Related Questions