Search code examples
javascriptflaskdom-eventsbulma

How do I close each instance of the same div class one a time using Javascript


What I'm trying to do is very straightforward: close every instance of a div each time the close button is clicked. What I'm getting instead is only the first clicked-on instance closes but the remaining ones can't.

I must say I come from Python and I'm not very familiar with Javascript. I think there is someway using ID instead of class? Here is my html (with Jinja) code for dynamically creating the objects I would want to close when clicked on:

{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages%}   
<div class="notification {{ category }} is-bold">
<button class="delete"></button>
{{ message }}
 </div>
  {% endfor %}
  {% endif %}
  {% endwith %}

And here is my Javascript code:

// notification remover
document.addEventListener('DOMContentLoaded', () => {

(document.querySelectorAll('.notification .delete') || []).forEach(($delete) => {
$notification = $delete.parentNode;
$delete.addEventListener('click', () => {
        $notification.parentNode.removeChild($notification);
});
});
});

Example of generated html:

<div class="notification is-info is-bold">
<button class="delete"></button>

<div class="notification is-info is-bold">
<button class="delete"></button>

<div class="notification is-info is-bold">
<button class="delete"></button>

Solution

  • Try this instead:

    document.addEventListener('DOMContentLoaded', () => {
    
      (document.querySelectorAll('.notification .delete') || []).forEach(($delete) => {
        $delete.addEventListener('click', (event) => {
          event.target.parentNode.remove();
        });
      });
    });
    

    The problem with your code is that you are setting $notification with the last one, so when the eventListener triggers $notification is always the last.