7

My Chrome Extension should modify a DOM element before the DOM is fully constructed, and in the best scenario, right after this DOM element is constructed.

For example, if I have a in my document, I want to wait until it is constructed, then directly modify it, before the rest of the DOM is constructed.

But I only managed to access the DOM before the element is constructed and after the entire DOM is constructed.

So how do I listen to the construction of a special element ?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Alexandre Kirszenberg
  • 35,938
  • 10
  • 88
  • 72

1 Answers1

4

You can use document.addEventListener with the DOMNodeInserted event. The nodes will be constructed and you will have a chance to modify them before they are inserted into the DOM. Something like the following should work.

function nodeInsertedCallback(event) {
  console.log(event);
};
document.addEventListener('DOMNodeInserted', nodeInsertedCallback);

 

Ray
  • 232
  • 3
  • 14
abraham
  • 46,583
  • 10
  • 100
  • 152
  • You could also include jQuery and use $(function(){}) to be run after the DOM has been created, before the page has loaded. – jjNford Mar 20 '12 at 12:59
  • Thanks for your help. This event is triggered before the DOM is fully constructed, but it doesn't allow me to modify the DOM content before it is shown. It only triggers for element dynamically added by scripts. – Alexandre Kirszenberg Mar 20 '12 at 15:54
  • 3
    The DOMNodeInserted event is deprecated. Use [Mutation Observers][1] instead. [1]: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – Ignat Apr 14 '16 at 06:52
  • When I test this DOMContentLoaded gets called before the event-handler for DOMNodeInserted – Markus Knappen Johansson Apr 22 '21 at 11:16