Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Javascript DOM manipulation while EJS loop

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda