Question

Is there any way to catch the document.createElement() event?

For example, somewhere, inside the <body> section I have

<script>
    var div = document.createElement("div");
<script>

Is it possible to track that event from the <head> section (using some addEventListener, mutation observer, or any other way)?

Note: I need to track the creation of the element, not the insertion

Était-ce utile?

La solution

Warning This code won't work in every browser. All bets are off when it comes to IE.

(function() {
  // Step1: Save a reference to old createElement so we can call it later.
  var oldCreate = document.createElement;

  // Step 2: Create a new function that intercepts the createElement call
  // and logs it.  You can do whatever else you need to do.
  var create = function(type) {
    console.log("Creating: " + type);
    return oldCreate.call(document, type);
  }

  // Step 3: Replace document.createElement with our custom call.
  document.createElement = create;

}());

Autres conseils

This is, similarly to other answers, an imperfect and incomplete solution (and is explicitly tested in only Chrome 34 on Windows 8.1):

// creating a function to act as a wrapper to document.createElement:
document.create = function(elType){
    // creating the new element:
    var elem = document.createElement(elType),
        // creating a custom event (called 'elementCreated'):
        evt = new CustomEvent('elementCreated', {
            // details of the custom event:
            'detail' : {
                // what was created:
                'elementType' : elem.tagName,
                // a reference to the created node:
                'elementNode' : elem
            }
    });
    // dispatching the event:
    this.dispatchEvent(evt);

    // returning the created element:
    return elem;
};

// assigning an event-handler to listen for the 'elementCreated' event:
document.addEventListener('elementCreated', function(e){
    // react as you like to the creation of a new element (using 'document.create()'):
    console.log(e);
});

// creating a new element using the above function:
var newDiv = document.create('div');

JS Fiddle demo.

References:

It's possible to create custom Events in javascript. And it's supported by all browsers too.

Check it out: http://jsfiddle.net/JZwB4/1/

document.createElement = (function(){
    var orig = document.createElement;
    var event = new CustomEvent("elemCreated");
    return function() { 
        document.body.dispatchEvent(event);
        orig.call(document,x); 
    };
})();


document.body.addEventListener('elemCreated', function(){
    console.log('created');
},false);

var x= document.createElement('p'); //"created" in console
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top