Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{% 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 %}

>Solution :

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"));
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading