Ad

Is There An "onload"-similar Event Listener For New Elements Beeing Added To The DOM In Javascript?

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>'
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad