Detect DOM Node Removal?

M

Matt Kruse

I have a reference to a DOM node. I want to know when it is removed
from the document, even if it was caused by a PARENT node being
removed!
(Firefox 3.5+, Chrome, Safari, Opera, don't care about IE)

I'll cover the obvious:

1) DOMNodeRemovedFromDocument: Doesn't bubble, and only fires on the
actual element removed, rather than for all children.

2) DOMNodeRemoved: Bubbles, so I can attach at document level, but
also doesn't fire on child elements

3) Catch one of the events above, then use querySelector() to see if
my child element is contained in it. But I can't query on an object
reference, so I would need a unique ID on the node, which I may not
have

4) I can do querySelectorAll('*') and manually look through all the
child nodes, but that seems so inefficient!

Any suggestions?

Matt Kruse
 
M

Martin Honnen

Matt said:
I have a reference to a DOM node. I want to know when it is removed
from the document, even if it was caused by a PARENT node being
removed!
(Firefox 3.5+, Chrome, Safari, Opera, don't care about IE)

I'll cover the obvious:

1) DOMNodeRemovedFromDocument: Doesn't bubble, and only fires on the
actual element removed, rather than for all children.

2) DOMNodeRemoved: Bubbles, so I can attach at document level, but
also doesn't fire on child elements

3) Catch one of the events above, then use querySelector() to see if
my child element is contained in it. But I can't query on an object
reference, so I would need a unique ID on the node, which I may not
have

You might want to check whether
http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition
is supported in your target browsers, that way you could check whether
your dom node is contained in any node reported by the mutation event
handlers. And IE has a contains method
http://msdn.microsoft.com/en-us/library/ms536377(v=VS.85).aspx, as
Opera and Safari copy the MSHTML/IE DOM they provide that method too, so
you wouldn't even need the DOM Level 3 compareDocumentPosition with
Opera/Safari.
It shouldn't also be too difficult to write your own contains method e.g.
function contains(container, containee) {
while (containee != null) {
if (container === containee) {
return true;
}
containee = containee.parentNode;
}
return false;
}
then call
if (contains(nodeReported, yourDomNode))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top