I need to determine if an HTML element is nested inside an element that is positioned absolutely. (1)*
e.g. I can do this:
function hasAbsoluteAncestor(obj){
while(obj != null){
if(window.getComputedStyle(obj,null).position == 'absolute'){
return true;
} else {
obj = obj.offsetParent;
}
}
return false;
}
//yes I'm aware IE doesn't play by the W3C game here... but I have a separate
//IE fix to enable this method in IE
//I'm also aware the above checks the "test" element too (ignore that for now)
but it seems fairly expensive to test for a rare case. I'm guessing 95% of the time it will be a tree of relative elements.
Is there any indicators that an element is nested in such a hierarchy? Any neat hacks that anyone knows?
Update: Based on Peter's comments about premature optimization I've altered my logic to return the coordinates to return 2 pairs... 1 pair (x,y) up to the root, another pair up the the first absolutely positioned parent. It still "feels" dirty, but doesn't appear to have any major impact to performance.
(1)* Why do I need this? I am adding a new absolutely positioned element below the tested element, setting the .left and .top properties... which (if) an ancestor is absolutely positioned, is the offset from that ancestor, not from the body/viewport thus I need to know if I need the position of the tested element as coordinates, realative to the body or a particular ancestor.