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>'
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM