I am trying to create a shop website with buttons called "add to cart" and have a few <div> elements. Every <div> element has a class and I want to dynamically add buttons to them by using their class name.
I created code that counts the number of the class, which I need to add to the button and combine it with for loop so it will add a button to every <div> element but for some reason, the loop is not working and it only adds to one div.
document.addEventListener('DOMContentLoaded', function() {
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = 'Press me';
button.className = 'btn-styled';
button.onclick = function() {
// ...
};
var classLength = document.getElementsByClassName("col-lg-4 col-md-6 mb-4").length;
var i;
for (i = 0; i < classLength; i++) {
var container = document.getElementsByClassName("col-lg-4 col-md-6 mb-4");
container[i].appendChild(button);
}
}, false);