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

后端 未结 11 994
滥情空心
滥情空心 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:40

    You could query document.getElementsByTagName("*").length or create a custom appendChild function like the folllowing:

    var append = function(parent, child, onAppend) {
      parent.appendChild(child);
      if (onAppend) onAppend(child);
    }
    
    //inserts a div into body and adds the class "created" upon insertion
    append(document.body, document.createElement("div"), function(el) {
      el.className = "created";
    });
    

    Update

    By request, adding the information from my comments into my post

    There was a comment by John Resig on the Peppy library on Ajaxian today that seemed to suggest that his Sizzle library might be able to handle DOM insertion events. I'm curious to see if there will be code to handle IE as well

    Following on the idea of polling, I've read that some element properties are not available until the element has been appended to the document (for example element.scrollTop), maybe you could poll that instead of doing all the DOM traversal.

    One last thing: in IE, one approach that might be worth exploring is to play with the onpropertychange event. I reckon appending it to the document is bound to trigger that event for at least one property.

提交回复
热议问题