Skip to content
Advertisement

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

Advertisement

Answer

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"));
  }
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement