skip to Main Content

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


  1. 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.

    var button = document.getElementById("button");
    button.outerHTML = button.outerHTML; // removes all existing event 
    
    button = document.getElementById("button");
    button.addEventListener("click", function() {
      window.alert("ping"); 
    }, false);
    <button id="button">click</button>
    Login or Signup to reply.
  2. Here is an alternative method …

    const button = document.getElementById('button');
    
    // cloneNode does not clone event listeners
    const clone = button.cloneNode(true); 
    
    // replace button with its clone
    button.parentNode.replaceChild(clone, button);
    
    // add new addEventListener(
    clone.addEventListener('click', () => {
      window.alert('ping'); 
    });
    

    Note: Generally speaking, DOM methods are more efficient and 5-10 times faster than innerHTML/OuterHTML.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search