How can I determine if a dynamically-created DOM element has been added to the DOM?

后端 未结 11 980
滥情空心
滥情空心 2020-12-02 20:07

According to spec, only the BODY and FRAMESET elements provide an \"onload\" event to attach to, but I would like to know when a dynamically-create

11条回答
  •  [愿得一人]
    2020-12-02 20:50

    The most straightforward answer is to make use of the Node.contains method, supported by Chrome, Firefox (Gecko), Internet Explorer, Opera, and Safari. Here is an example:

    var el = document.createElement("div");
    console.log(document.body.contains(el)); // false
    document.body.appendChild(el);
    console.log(document.body.contains(el)); // true
    document.body.removeChild(el);
    console.log(document.body.contains(el)); // false
    

    Ideally, we would use document.contains(el), but that doesn't work in IE, so we use document.body.contains(el).

    Unfortunately, you still have to poll, but checking whether an element is in the document yet is very simple:

    setTimeout(function test() {
      if (document.body.contains(node)) {
        func();
      } else {
        setTimeout(test, 50);
      }
    }, 50);
    

    If you're okay with adding some CSS to your page, here's another clever technique that uses animations to detect node insertions: http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/

提交回复
热议问题