Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!