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
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/