Home >Web Front-end >JS Tutorial >How Can I Remove Event Listeners from DOM Objects in JavaScript?
To remove all event handlers from an object, you can clone the element and replace it with the clone:
<code class="javascript">var clone = element.cloneNode(true);</code>
This method preserves attributes and children, but not changes to DOM properties.
You can remove event handlers with anonymous functions by storing a reference to the returned function and creating a separate function to remove all events:
<code class="javascript">var _eventHandlers = {}; const addListener = (node, event, handler, capture = false) => { if (!(event in _eventHandlers)) { _eventHandlers[event] = [] } _eventHandlers[event].push({ node: node, handler: handler, capture: capture }) node.addEventListener(event, handler, capture) } const removeAllListeners = (targetNode, event) => { _eventHandlers[event] .filter(({ node }) => node === targetNode) .forEach(({ node, handler, capture }) => node.removeEventListener(event, handler, capture)) _eventHandlers[event] = _eventHandlers[event].filter( ({ node }) => node !== targetNode, ) }</code>
This allows you to add and remove event listeners using:
<code class="javascript">addListener(div, 'click', eventReturner(), false) removeAllListeners(div, 'click')</code>
If you use an anonymous function to handle events, you can simply add and remove it directly:
<code class="javascript">function handler() { dosomething(); } div.addEventListener('click',handler,false);</code>
The above is the detailed content of How Can I Remove Event Listeners from DOM Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!