Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!