最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AppendChild in `for` loop or `forEach ` - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Oct 18, 2020 at 5:03 Shashank ChaudharyShashank Chaudhary 1622 silver badges12 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

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));
}

You need to call cloneNode() with true to clone along with its descendants/children.
Also first get the list of elements once, and then iterate through it and append the button, like.

let button = document.createElement('div');
button.innerHTML = "<a class='btn hero-btn'>Add to cart</a>";

let productSections = document.querySelectorAll('.single-product');
for (let i=0 ; i < productSections.length ; i++){
   productSections[i].appendChild(button.cloneNode(true));
)
发布评论

评论列表(0)

  1. 暂无评论