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

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

    In a perfect world you could hook the mutation events. I have doubts that they work reliably even on standards browsers. It sounds like you've already implemented a mutation event so you could possibly add this to use a native mutation event rather than timeout polling on browsers that support those.

    I've seen DOM-change implementations that monitor changes by comparing document.body.innerHTML to last saved .innerHTML, which isn't exactly elegant (but works). Since you're ultimately going to check if a specific node has been added yet, then you're better off just checking that each interrupt.

    Improvements I can think of are using .offsetParent rather than .parentNode as it will likely cut a few parents out of your loop (see comments). Or using compareDocumentIndex() on all but IE and testing .sourceIndex propery for IE (should be -1 if node isn't in the DOM).

    This might also help: X browser compareDocumentIndex implementaion by John Resig.

提交回复
热议问题