I was not able to get the elements into array by getElementsByClassName

Viewed 79
{% block scripts %}
    

    <script>
       console.log('hello world')
       const modalBtns = [...document.getElementsByClassName('btn btn-link modal-button')]
    
        modalBtns.forEach(modalBtn=> modalBtn.addEventListener("click", function(){
          console.log(modalBtn)
        })) 

  </script>
{% endblock %}

{% block content %}

<div class="h1">Quiz List</div>
<hr>
{% for obj in object_list %}
 

     <button 
      class="btn btn-link modal-button"
      data-pk='{{obj.pk}}'
      data-quiz='{{obj.name}}'
      data-questions='{{obj.number_of_questions}}'
      data-difficulty='{{obj.difficulty}}'
      data-time='{{obj.time}}'
      data-pass='{{obj.required_score_to_pass}}'
      data-bs-toggle="modal" 
      data-bs-target="#quizStartModal">{{obj.name}}</button><br>

{% endfor %}
{% endnlock %}

Not able to see the output in the console and the elements which are in the class 'modal-button' are also not inserting into the array of modalBtns

2 Answers

While the time of execution the buttons don't exist since they are not rendered, so instead add buttons first then add the JS

{% endblock %}
{% block content %}
    
<div class="h1">Quiz List</div>
<hr>

{% for obj in object_list %}

<button
  class="btn btn-link modal-button"
  data-pk='{{obj.pk}}'
  data-quiz='{{obj.name}}'
  data-questions='{{obj.number_of_questions}}'
  data-difficulty='{{obj.difficulty}}'
  data-time='{{obj.time}}'
  data-pass='{{obj.required_score_to_pass}}'
  data-bs-toggle="modal" 
  data-bs-target="#quizStartModal">
  {{obj.name}}
</button>
<br>


{% endfor %}
{% endnlock %}

{% block scripts %}
    
<script>
  console.log('hello world')
  const modalBtns = [...document.getElementsByClassName('btn btn-link modal-button')]
        
  modalBtns.forEach(modalBtn=> modalBtn.addEventListener("click", function(){
    console.log(modalBtn)
  })) 
    
</script>

Looks like the dom isn't rendering the buttons before the script tag invokes your JS.

Try wrapping the script code inside a load event listener.

So your Code in the script tag goes from this:

<script>
 console.log('hello world')
 const modalBtns = [...document.getElementsByClassName('btn btn-link modal-button')]
       
 modalBtns.forEach(modalBtn=> modalBtn.addEventListener("click", function(){
   console.log(modalBtn)
 })) 
   
</script>

To this:

<script>
window.addEventListener('load', (event) => {
  console.log('hello world');

  const modalBtns = [...document.getElementsByClassName('btn btn-link modal-button')];
  modalBtns.forEach(modalBtn=> modalBtn.addEventListener("click", function(){
    console.log(modalBtn);
  }));

});
</script>
Related