0

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);
1
  • you need to create OR clone the button INSIDE the loop Commented Oct 24, 2020 at 18:28

2 Answers 2

1

Thank everyone for the help it really was helpful i fixed it with the following code as you suggested and it seems to work

document.addEventListener('DOMContentLoaded', function() {
  var classLength = document.getElementsByClassName("col-lg-4 col-md-6 mb-4").length;
  var i;
  for (i = 0; i < classLength; i++){
  var button = document.createElement('button');
  button.type = 'button';
  button.innerHTML = 'Press me';
  button.className = 'btn-styled';

  button.onclick = function() {
    // ...
  };

  var container = document.getElementsByClassName("col-lg-4 col-md-6 mb-4");
  container[i].appendChild(button);
  }
}, false);
Sign up to request clarification or add additional context in comments.

1 Comment

I would say my answer is more elegant... But hey, It is your site
0

You need to clone or create the button inside the loop

Note I added the click event listener to the container

const clicked = (e) => console.log("clicked", e.target.parentNode.firstChild.textContent)
window.addEventListener('load', function() {
  var button = document.createElement('button');
  button.type = 'button';
  button.innerHTML = 'Press me';
  button.className = 'btn-styled';

  [...document.querySelectorAll(".col-lg-4.col-md-6.mb-4")] // note the selector
  .forEach(div => div.appendChild(button.cloneNode(true)))

  document.getElementById("container").addEventListener("click", clicked);
})
<div id="container">
  <div class="col-lg-4 col-md-6 mb-4">1. </div>
  <div class="col-lg-4 col-md-6 mb-4">2. </div>
  <div class="col-lg-4 col-md-6 mb-4">3. </div>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.