Search code examples
javascriptfor-loopforeachappendchild

AppendChild in `for` loop or `forEach `


I have several classes with single-product as className. I am trying to add the buttons to all of them using appendChild in for loop in javascript. But it doesn't seem to be working. I don't understand why?
I am taking them in an array using querySelectorAll.
let products = document.querySelectorAll('.single-products') then I created an element div which contains my button.

let button = document.createElement('div');
button.innerHTML = "<a class='btn hero-btn'>Add to cart</a>";
for (let i=0 ; i < products.length ; i++){document.querySelectorAll('.single-product')[i].appendChild(button.cloneNode())

I also tried forEach with this as the param but even that did not work.


Solution

  • Your program would never enter the loop and it also generates ReferenceError because products is never defined to find it's length. You have to define it before the program enters the for loop. And the other thing is cloneNode() only creates the clone at the base level. You have to use cloneNode(true) to clone it and it's descendents as well. Here is the fix for your code:

    let button = document.createElement("div");
    
    button.innerHTML = "<a class='btn hero-btn'>Add to cart</a>";
    
    let products = document.querySelectorAll(".single-product");
    
    for (let i = 0; i < products.length; i++) {
      products[i].appendChild(button.cloneNode(true));
    }