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

115
Visualizações
addEventListener not working for a HTML Button that is within a Django for loop

I am trying to call a function when an HTML button is clicked, but right now, a console.log is supposed to run when the button is clicked, but nothing appears in the console. This button is within a for loop in Django and is being selected via querySelector through its class. I want only the specific button that is clicked to be selected, but I do not know if anything is being selected because nothing happens when the button is clicked.

javascript

document.addEventListener('DOMContentLoaded', function(){
    document.querySelector('.edit_button').addEventListener('click', () => console.log("test"));
});

html

{% for post in page_obj.object_list %}
            <div class = "individual_posts">
                <h6 id = "post_itself">{{ post.post }}</h6>
                {% if post.user == request.user %}
                    <button id="editButton" class="edit_button">Edit</button>
                {% endif %}
            </div>
{% endfor %}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

querySelector only returns the first element that matches the query. Use querySelectorAll to get all elements that are matches. Loop over result and add the event listeners per button.

document.addEventListener('DOMContentLoaded', function(){
  const buttons = document.querySelectorAll('.edit_button');
  for (const button of buttons) {
    button.addEventListener('click', () => console.log("test"));
  }
});
about 4 years ago · Santiago Gelvez 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