I’m trying to attach an onclick event listener to an existing element (notably not a button
with a form
, it’s a simple div
) on a webpage through a userscript. However, it appears that, even though to my knowledge adding an event listener in an anonymous function shouldn’t run afoul of timeout rules for the userscript existing, it doesn’t attach anything (or, possibly, it does, but then the userscript times out and the anonymous function stops existing, causing the event listener to fall off. Am I misunderstanding something fundamental about the scope of user scripts?
I’ve tried attaching it to the button in the following manner. This is not caused by some obscure race condition with re-binding outerHTML to itself, because even without that line the event listener is not added.
var button = document.getElementById("button");
button.outerHTML = button.outerHTML; // removes all existing event listeners on the element
button.addEventListener("click", function() {
window.alert("ping"); // or any other function body
}, false);
Firefox 112.0.2
2
Answers
It does not work because when you do
button.outerHTML = button.outerHTML;
the button you originally referenced is no longer the button in the DOM. You are replacing that button with a new button.You would need to select the button again.
Here is an alternative method …
Note: Generally speaking, DOM methods are more efficient and 5-10 times faster than
innerHTML/OuterHTML
.