How to take away all match listeners from a DOM component


Printed at

Up to date at

Studying time
1min

Disposing of match listeners from DOM components is beautiful hectic since you should have the registered match handler serve as handy.

serve as handleEvent() {  }


report.querySelector('button')
  .addEventListener('click on', handleEvent);




report.querySelector('button')
  .removeEventListener('click on', handleEvent);

With fairly fashionable JavaScript, it’s good to additionally use AbortSignals or the as soon as config choice to take away match listeners, however what if it is not your supply code that is including match listeners? What if there may be one hectic third celebration script messing together with your occasions and you have got to stay it?

Nowadays I realized a few nuclear choice to take away all present match listeners.

const button = report.querySelector('button);



button.replaceWith(button.cloneNode(true));

Growth! And that is the reason it — changing a DOM component with a cloned model of itself gets rid of all up to now registered match handlers. Beautiful to hand!

Tournament handlers outlined in an on* HTML characteristic might be preserved whilst you clone a DOM component.


<button onclick="console.log('Nonetheless right here!')"`>click on me</button>

If you wish to see this development in motion, right here we cross. 👇


const button = report.getElementById('cta-btn')

for(let i = 0; i < 3; i++) {
  button.addEventListener('click on', () => {
    alert(`${i + 1}. match listener of three...`);
  });
}

report.getElementById('nuke-btn')
  .addEventListener('click on', (match) => {
    
    
    button.replaceWith(button.cloneNode(true));

    alert('All present match listeners cleared!');
  });
Was once this snippet useful?
Sure? Cool! You may want to take a look at Internet Weekly for extra snippets. The remaining version went out 2 days in the past.

Similar Subjects

Similar Articles

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back To Top
0
Would love your thoughts, please comment.x
()
x