I know I could probably just use Element#up to check for the body
node, but that is an expensive query and I'm trying to make this as
native as possible.
At first I thought the built-in ownerDocument property would work, but
it doesn't seem to perform as I expect it to, which would be:
"The document that this node is in, or null if the node is not inside of one."
Short of using .up('body'), is there a native method of checking if an
element has been orphaned?
-justin
Was playing around with this some more, and realized I my best option
is to just attempt to fetch the element in question. Makes for a
pretty quick operation if the ID is present, otherwise the alternate
method would be crawling back up the DOM from the element to find the
body element (assuming the body has not been removed).
This seems to do the trick: http://pastie.org/224848
I believe this could be shortened like so:
Element.addMethods({
isOrphaned: function(element){
if (element.id) {
return !!element.ownerDocument.getElementById(element.id);
}
return !!element.up('body');
}
});
This is what I got now, works great.
Element.addMethods({
isOrphaned: function(element){
if (element.id) return !element.ownerDocument.getElementById(element.id);
return !element.up('body');
});
-justin
Element.addMethods({
isOrphaned: function(element){
if (element.sourceIndex < 1) return true; // for IE only
if (element.id) return !element.ownerDocument.getElementById(element.id);
return (element.descendentOf ?
!element.descendentOf(document.body) : element.up('body'));
}
});
-justin
In my usage that is unnecessary since I'm calling that method directly
on an already instantiated element object, but it is a good addition
for the Element.isOrphaned('some-id') usage.
The problem I was having was a spelling error, descendent vs. descendant :)
Your optimization to the last line is nice too.
-justin