javascriptforeachremoveeventlistener

removeEventListener in forEach


Friends!

How in JS to hang such a handler on all the buttons of the collection, so that when each of them is clicked, something happens, and the handler is removed from all the buttons in the collection? I managed to make it so that it is removed only from the one I click on (while the class is removed from everyone):

document.querySelectorAll('.string').forEach((field, i, fields) => {
  const listen = () => {
    const res = document.createElement('div');
    res.textContent = field.textContent;
    document.getElementById('container').append(res);

    fields
      .forEach((field, i, fields) => {
        field.classList.remove('bright');
        field.removeEventListener('click', listen);
      });
  };

  field.addEventListener('click', listen);
});

https://codepen.io/andreymi/pen/RwMOvOq


Solution

  • your code isnt working because the listen function get recreated for each element

    var fields=document.querySelectorAll('.string');
    
    const listen = () => {
      const res = document.createElement('div');
      res.textContent = this.textContent;     // <- note 'this' keyword
      document.getElementById('container').append(res);
    
      fields.forEach((field, i, fields) => {
        field.classList.remove('bright');
        field.removeEventListener('click', listen);
        console.log('remove',i);
      });
    };
    
    fields.forEach((field, i, fields) => {
      console.log('add',i);
      field.addEventListener('click', listen);
    });