2

Does Javascript provide an event listener similar to onload that will be invoked if an element is added to the DOM via innerHTML?

I know <body onload="alert('hi');">...</body>. But it does only work in the beginning when the whole site is loaded.. Is it somehow possible to add an element via innerHTML = ... that triggers an event listener instantly that it contains?

It should look like this and it has to be an inline-HTML listener like this:

elementxy.innerHTML = '<b onload="dosth()">....</b>'
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hardfork
  • 2,470
  • 1
  • 23
  • 43
  • 2
    That method requires an *external* listener, but I'm pretty sure OP is asking about a method for an *internal* inline listener to be invoked – CertainPerformance Nov 06 '19 at 08:25
  • You could use a MutationObserver. That can tell you when elementxy's children change, like when you add new html to it. That listener can then trigger a different event elsewhere. But you do have to set up the observer before changing the innerHTML, so not as easy as just adding some attributes to the HTML you'll insert. Could you specify what kind of event? Could you just dispatch it manually after changing the innerHTML? – Shilly Nov 06 '19 at 08:39
  • @CertainPerformance is right. It has to be an inline listener in an HTML-tag. I added that to the question. – hardfork Nov 06 '19 at 08:53
  • I tried DOMSubtreeModified ? https://developer.mozilla.org/en-US/docs/Archive/Events/DOMSubtreeModified but it causes an infinite loop as you cannot set an event listener in a specific div = > you cant modified anything unless you unbind first. – PhilMaGeo Nov 06 '19 at 09:14

1 Answers1

2

This is a really bad hack, but you can create an invisible <img> tag with an onerror attribute and a src that results in an error:

const dosth = () => {
  console.log('dosth');
};

div.innerHTML = '<b>b content<img style="display: none;" onerror="this.remove(); dosth()" src="badsrc"></b>';
<div id="div"></div>

This is one reason why inserting untrustworthy HTML is a bad idea - even with innerHTML, it allows for arbitrary code execution.

Regardless, it's best to avoid inline handlers entirely.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320