1

If a div has an event, and the function is an anonymous function passed in some long minified JS. How can I from console remove that event?

I have tried cloning and replacing, or replacing outerHTML, but both methods affect all the innerHTML.

Is there a way to remove the eventListener without referencing the function itself? Just remove all the eventlisteners attached to the div?

Ray C
  • 547
  • 2
  • 7
  • 24
  • `but both methods affect all the innerHTML.` Do you mean that the problem with this is that any listeners attached to *children* get removed too, which you don't want? (you only want the listener attached to the outer div to be removed?) Or, what is the issue with changing the `innerHTML`? – CertainPerformance Nov 19 '18 at 01:58
  • One answer is easy: No to this: _Is there a way to remove the eventListener without referencing the function itself?_ the reason is due to how JS compares Objects (function objects in this case). They are compared by reference - so both `add..` and `remove...` must use a _reference_ to the same object. – Randy Casburn Nov 19 '18 at 02:14
  • @CertainPerformance yes, do not affect any inner events or elements, or their state. – Ray C Nov 19 '18 at 02:20
  • @RandyCasburn What I don't understand is you can easily remove attributes like style, classes etc... without having to reference anything other than getElementById.thing = null – Ray C Nov 19 '18 at 02:21
  • right - that's because the run time is looking up the function used as an event handler in what amounts to a lookup table. It evaluates which event to remove based upon a comparison of the provided reference (to the function) and all the ones stored in the lookup table. It is the comparison that differentiates this particular thing. – Randy Casburn Nov 19 '18 at 02:23

1 Answers1

0

One option would be to replace the div that has the listener you want to remove with an identical div (but without the listener) - iterate through the original div's childNodes and append them to the new div. As you can see in the example below, the #outer container gets replaced, but the listener on #inner is still preserved:

const [outer, inner] = ['outer', 'inner'].map(id => document.getElementById(id));
outer.addEventListener('click', () => console.log('outer clicked'));
inner.addEventListener('click', () => console.log('inner clicked'));

const outerParent = outer.parentElement;
const newOuter = outer.cloneNode(false);
/*
 * make sure to use false above for a shallow copy (no children);
 * if you create and use a deep copy, listeners attached to outer's old children won't be preserved
 * (the listeners don't get copied)
 */
 
[...outer.childNodes].forEach(child => {
  newOuter.append(child)
});
outerParent.replaceChild(newOuter, outer);
<div id="outer">
  inside outer
  <div id="inner">
    inner
  </div>
  inside outer
</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320