28

I need to create an event listener such that, when a new element is added to the document, or any of its child, my event handler gets called.

Any ideas how to do this using?

informatik01
  • 16,038
  • 10
  • 74
  • 104
zeacuss
  • 2,563
  • 2
  • 28
  • 32
  • @zeacuss: go here http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener – Krish Mar 12 '12 at 12:29

3 Answers3

30
.bind('DOMNodeInserted DOMNodeRemoved')

this are the events to check element is inserted or removed.

bind on parent element this event.

and call your function in handler

js fiddle demo : http://jsfiddle.net/PgAJT/

click here for example... http://help.dottoro.com/ljmcxjla.php

sandeep
  • 2,244
  • 1
  • 23
  • 38
  • 14
    it is now deprecated.. see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events – yomexzo Jul 31 '14 at 09:05
28

Mutation events are deprecated, use Mutation Observer instead. You can also use arrive.js library, it uses Mutation Observer internally and provides a nice simple api to listen for elements creation and removal.

document.querySelector('#container').arrive('.mySelector', function(newElem){
    // newElem is the newly injected element
});
Uzair Farooq
  • 2,402
  • 3
  • 24
  • 37
  • 2
    Very nice library! Solved my current issue and will definitely be using it on future projects. Thanks, Uzair! – Mikael Kessler Sep 17 '14 at 20:14
  • I could get this to work, but I added console.log snippets before and after the action (calling selectize on the selects) and I have a function that inserts 4 selects into a HTML table. Instead of triggering 4x, it kept triggering until code hang. Is there a way to prevent that? I used onlyOnce:true and it didn't crash out, but it only did it for the first select. – Robert Mar 31 '23 at 18:13
5

DOMNodeInserted is deprecated in DOM Level 3 recommendation. using them slows browsers down (they say). depending on what you need it for, it might make sense to trigger a custom event inside the code where you insert the element.

Christian
  • 3,551
  • 1
  • 28
  • 24