有没有办法跟踪document.createElement()的元素创建?

时间:2014-04-15 22:10:00

标签: javascript dom javascript-events mutation-observers

有没有办法赶上document.createElement()事件?

例如,在<body>部分的某个地方,我有

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

是否可以从<head>部分跟踪该事件(使用一些addEventListener,变异观察器或任何其他方式)?

注意:我需要跟踪元素的创建不是插入

3 个答案:

答案 0 :(得分:3)

警告此代码不适用于所有浏览器。所有赌注都归于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;

}());

答案 1 :(得分:2)

与其他答案类似,这是一个不完美且不完整的解决方案(并且仅在 在Windows 8.1上的Chrome 34中进行了明确测试):

// 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

参考文献:

答案 2 :(得分:1)

可以在javascript中创建自定义事件。它也受到所有浏览器的支持。

检查出来: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