How can I assign the var to the innerHTML of individual buttons when the buttons are created through a for loop?

Question:

Using Django, my buttons are created using a for loop and assigned values based on model values.

Based on which button is click, I want to update the "new_note_header" with the innerHTML of the button.

I have created the following JavaScript, which works but only when the first button clicked.

<script>
function ProjectSelect () {
    var x = document.querySelector('button').innerHTML;
    document.getElementById('new_note_header').innerHTML = x;
}

document.addEventListener('DOMContentLoaded', function () {
    document.querySelector('button').onclick = ProjectSelect;
});


</script>

<div class = project_container>
    {% for project in projects %}
        <button class = individual_project_container>
            {{ project }}
        </button>
    {% endfor %}
</div>
<div class = note_header_container>
    <div class = new_note_header, id = new_note_header>
        New Note
    </div>
</div>

I would be grateful for any help in adapting the JavaScript so it works for all buttons clicked.

Asked By: RoyKeane94

||

Answers:

querySelector will take the FIRST element that satisfies the selector

You could use querySelectorAll and assign a click event handler to each, but I recommend using delegation:

document.addEventListener('DOMContentLoaded', function() {
  const nnHead = document.getElementById('new_note_header');
  document.getElementById("project_container").addEventListener("click", e => {
    const tgt = e.target.closest("button");
    if (!tgt.matches(".individual_project_container")) return; // not a button
    nnHead.textContent = tgt.textContent.trim();
  });
});

<div class="project_container" id="project_container">
  <button class="individual_project_container">Project 1</button>
  <button class="individual_project_container">Project 2</button>
  <button class="individual_project_container">Project 3</button>

</div>
<div class="note_header_container">
  <div class="new_note_header" id="new_note_header">
    New Note
  </div>
</div>

Answered By: mplungjan