Alex Rivera | Logout

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

Asked 2008-10-20T22:38:38.377
42

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-created DOM element has been added to the DOM in JavaScript.

The super-naive heuristics I am currently using, which work, are as follows:

  • Traverse the parentNode property of the element back until I find the ultimate ancestor (i.e. parentNode.parentNode.parentNode.etc until parentNode is null)

  • If the ultimate ancestor has a defined, non-null body property

    • assume the element in question is part of the dom
  • else

    • repeat these steps again in 100 milliseconds

What I am after is either confirmation that what I am doing is sufficient (again, it is working in both IE7 and FF3) or a better solution that, for whatever reason, I have been completely oblivious to; perhaps other properties I should be checking, etc.


EDIT: I want a browser-agnostic way of doing this, I don't live in a one-browser world, unfortunately; that said, browser-specific information is appreciated, but please note which browser you know that it does work in. Thanks!

Edit
Report

1 Answer

0
var finalElement=null; 

I am building dom objects in a loop, when the loop is on the last cycle and the lastDomObject is created then:

 finalElement=lastDomObject; 

leave loop:

while (!finalElement) { } //this is the delay... 

The next action can use any of the newly created dom objects. It worked on the first try.

answered 2013-04-11T00:28:08.360

Your Answer