Just for curiosity I want to get an event every time i add html code to a div like this
const xData = 40;
const container = document.querySelector('.container');
container.innerHTML = `<div class="container_Addons">${xData}</div>`;
container.addEventListener('i dont know',function(){
console.log("you have just added some exotic stuff!");
});
for (i= 0; i<10;i++){
container.innerHTML += `<div class="container_Addons">${i}st ${xData}</div>`;
};
to get an listener working every time i add html code
2
Answers
You can use
MutationObserver
withchildList: true
to subscribe to specific DOM changes:Note, however, that your
MutationObserver
‘s callback won’t be invoked for every single statement that’s executed that updates.innerHTML
(as they might cause a single paint, like the ones inside thefor
in the example above), but you can get the list of updated elements frommutationsList
.However, if new elements are added at different points in time (like the one inside
setTimeout
), your callback will be invoked for each update.Using MutationObserver is quite easy to watch an element’s
childList
change:The
innerHTML
constantly changes an element’s full contents, therefore I opted for the much more suitable Element.append() method – in order to only be notified for that one specific child insertion. You can as well use.innerHTML =
instead of.append()
, but in such case you’ll have to do extra useless and complicated work to detect what is exactly that was newly inserted.