Oguntoye
Oguntoye

Reputation: 685

How do I append cloned html elements to parent element on click using a loop?

The following piece of javascript is supposed to clone an HTML node, then append the clone to the originals' parent 50 times using a loop.

Right now, it only adds appends one clone per click. the expected behavior is fifty clones appended at once.

CODE

// placeholder generators
document.querySelector(".dummy-load-home").addEventListener("click", gen)

function gen(){
const clone = document.querySelector('.card.featured').cloneNode(true);
let count = 0;
while(count < 50) {
    document.querySelector('.card.featured').parentNode.appendChild(clone);
    count++
  }
}

Kindly draw to my attention what I have done wrong.

Upvotes: 1

Views: 1146

Answers (2)

Piyush Bansal
Piyush Bansal

Reputation: 1723

Use the following function:

    function gen(){
    let count = 0;
    while(count < 50) {
const clone = document.querySelector('.card.featured:last-child').cloneNode(true);
        document.querySelector('.card.featured').parentNode.appendChild(clone);
        count++
      }
    }

Hope it works.

Upvotes: 1

Rose Robertson
Rose Robertson

Reputation: 1256

That's because it's re-appending the same clone over and over again. So even though it does do it 50 times it doesn't look like anything is happening. You'd need to generate a new clone in the loop as well.

function gen(){
  const elementToClone = document.querySelector('.card.featured');
  let count = 0;
  while(count < 50) {
    let clone = elementToClone.cloneNode(true);
    document.querySelector('.card.featured').parentNode.appendChild(clone);
    count++;
  }
}

You could probably optimize it a bit more too by caching the parent node so you don't have to search for it every iteration of the loop -

function gen(){
  const elementToClone = document.querySelector('.card.featured'),
        parentNode = elementToClone.parentNode;

  let count = 0;     
  while(count < 50) {
    let clone = elementToClone.cloneNode(true);
    parentNode.appendChild(clone);
    count++;
  }
}

And then maybe even better - creating a DocumentFragment and appending that at the very end so that less re-paints have to happen (although TBH I am not 100% on the performance gains of this one. Logically it seems like it must but I'm just doing a bit of research right now to confirm and so far haven't found anything conclusive)

function gen(){
  const elementToClone = document.querySelector('.card.featured'),
        parentNode = elementToClone.parentNode,
        fragment = new DocumentFragment();

  let count = 0;     
  while(count < 50) {
    let clone = elementToClone.cloneNode(true);
    fragment.appendChild(clone);
    count++;
  }

  parentNode.appendChild(fragment);
}

Upvotes: 2

Related Questions