0

I have few hours on this problem and I am still stuck on it, can't seem to find a solution. In short, I am trying to manipulate each div from an EJS loop. I simplified the problem so can be easier to understand.

  <% for(let i of products) { %>
        <div> 
           // products irrelevant code
        </div>

        <div  class="d-flex justify-content-around">
            <i class="btn btn-light fas fa-heart fa-lg" id="wishlist" style="color:grey;"></i>
        </div>
    <% } %>


    <script>
        const heart = document.getElementById("wishlist")
      
        heart.addEventListener("click", ()=> {
        heart.style.color = "red";
      });
      
    </script>

On my showpage, when I click on the element it changes the color as it should, but just for the first product. I am not sure why is not hitting each div in the loop. How can I change the color for each specific element?

1 Answers1

0

Remove id wishlist on i and add container id for parent div.

AddEventListener on container id div, and modify target clicked element as shown in below code.

const heart = document.getElementById("container");
heart.addEventListener("click", (e) => {
  const tgt = e.target;
  if (tgt.classList.contains('fa-heart')) {
    tgt.style.color = "red";
  }
});
.red {
  color: red
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

<div id="container">
  <div>
    // products irrelevant code
  </div>

  <div class="d-flex justify-content-around" id="container">
    <i class="btn btn-light fas fa-heart fa-lg" style="color:grey;"></i>
  </div>
  <div>
    // products irrelevant code
  </div>

  <div class="d-flex justify-content-around">
    <i class="btn btn-light fas fa-heart fa-lg" style="color:grey;"></i>
  </div>
  <div>
    // products irrelevant code
  </div>

  <div class="d-flex justify-content-around">
    <i class="btn btn-light fas fa-heart fa-lg" style="color:grey;"></i>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
navnath
  • 3,548
  • 1
  • 11
  • 19