简体   繁体   中英

How do I know when a DOM-element is created?

I'm trying to acquire a reference for a specific QUnit DOM-element, as soon as this element is created. I can get it by using window.setTimeout , but is there an event-driven way to do it?

I have tried various approaches, but only the least satisfying ( window.setTimeout ) actually works:

window.onload = function() {
    var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
    console.log("from window.onload: qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
};

returns null

document.addEventListener("DOMContentLoaded", function(event) {
   var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
    console.log("from document.addEventListener(DOMContentLoaded): qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
});

returns null

document.addEventListener("load", function(event) {
    var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
    console.log("from document.addEventListener(load): qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
});

is never executed

window.setTimeout(function() {
    var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
    console.log("from window.setTimeout: qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
}, 2000);

returns the DOM-reference

The code can be befiddled at this jsfiddle . Note that the fiddle only logs the one successful DOM-reference. The others are somehow silenced.

This is how it looks when executed locally:

在此处输入图片说明

There is the DOMMutationObserver , which allows you to subscribe to changes to the DOM.

var mutationObserver = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        var id = 'qunit-testrunner-toolbar',
            added = mutation.addedNodes,
            removed = mutation.removedNodes,
            i, length;

        for (i = 0, length = added.length; i < length; ++i) {
          if (added[i].id === id) {
            //  qunit-testrunner-toolbar was added
          }
        }

        for (i = 0, length = removed.length; i < length; ++i) {
          if (removed[i].id === id) {
            //  qunit-testrunner-toolbar was removed
          }
        }
      });
    });

mutationObserver.observe(target, {childList: true});

If you need to stop listening for changes (as the amount of changes to the DOM can be huge ;) ), you can simply use mutationObserver.disconnect() .

If the #qunit-testrunner-toolbar is not the node that is added (but instead is part of another structure), the checks above will not work. If that is the case you can replace the added[i].id === id with something like

if (added[i].querySelector('#qunit-testrunner-toolbar')) {
  // it was added
}

I should at least mention the now deprecated Mutation Events , which seem more convenient to implement but were pretty slow and inaccurate.

document.addEventListener('DOMNodeInserted', function(e) {
  if (e.target.id === 'qunit-testrunner-toolbar') {
  }
});

Tempting to use, but don't as it is deprecated.

Everything you put in JSFiddle's javascript is already wrapped in onload event (so window.onload will never be fired again - it is already fired). Change it to "Javascript" -> "Load time" -> "No wrap - in <head>" and you will get all of your events fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM