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.
2 Answers
Reset to default 4Your 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));
)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744120152a4559361.html
评论列表(0条)