I'm trying to give a button inside all my class .why-text. I selected them by document.querySelectorAll('.why-text'); And use the loop "for" to append button to all the class. But it doesn't working. This is my code:
var btnAddCart = document.createElement("button");
btnAddCart.innerHTML = "Add";
var WhyTxt = document.querySelectorAll('.why-text');
for (let i = 0; i < WhyTxt.length; i ) {
WhyTxt[i].appendChild(btnAddCart);
}
CodePudding user response:
You create only one button, then keep appending that very same button to n locations, so it ends up in the last of those. Appending an element that is already in the DOM effectively moves that element.
You need to create the button in the loop to have individual buttons:
const WhyTxt = document.querySelectorAll('.why-text');
for (let i = 0; i < WhyTxt.length; i ) {
const btnAddCart = document.createElement("button");
btnAddCart.textContent = "Add";
WhyTxt[i].appendChild(btnAddCart);
}
That being said, your code can also be simplified by alot:
for (let el of document.querySelectorAll(".why-text")) {
el.append(Object.assign(document.createElement("button"),{textContent:"Add"}));
}
CodePudding user response:
You have to create the element each time, within the loop. It could be made outside the looped and cloned within it but you are only making one element in the current structure so it can only be added once.
This working snippet uses the simple approach of making a new button element inside each loop of the parent collection.
var WhyTxt = document.querySelectorAll('.why-text');
console.log(WhyTxt.length);
for (let i = 0; i < WhyTxt.length; i ) {
var btnAddCart = document.createElement("button");
btnAddCart.innerHTML = "Add";
WhyTxt[i].appendChild(btnAddCart);
}
div {
height: 2em;
background: yellow;
}
<div ></div><br>
<div ></div><br>
<div ></div><br>
<div ></div><br>
<div ></div><br>