views:

773

answers:

5

I am trying to do positioning in JavaScript. I am using a cumulative position function based on the classic quirksmode function that sums offsetTop and offsetLeft for each offsetParent until the top node.

However, I am running into an issue where the element I'm interested in has no offsetParent in Firefox. In IE offsetParent exists, but offsetTop and offsetLeft all sum up to 0, so it has the same problem in effect as in Firefox.

What would cause an element that is clearly visible and usable on the screen to not have an offsetParent? Or, more practically, how can I find the position of this element in order to place a drop-down beneath it?

+3  A: 

If the document hasn't finished loading then offsetParent can be null

Greg
+1  A: 

This is an old question, but I have another case. If you manipulate the DOM, you may end up with a null offsetParent. See: http://weblogs.asp.net/rajbk/archive/2006/11/29/ie-6-7-unspecified-error-when-accessing-offsetparent-javascript.aspx

Mark
A: 

I don't know about the offsetParent being null but it is not uncommon for the offsetTop to be zero if, say, you have a TD inside a TR, because they will both be at the same vertical position.

Carl
A: 

I have run into this problem when the sibling just to the left of the element is hidden:

<div id="parent">
  <div id="element1">some stuff</div>
  <div id="element2" style="display: none">some hidden stuff</div>
  <div id="element3">child whose offset we want</div>
</div>

I've run into the case where the offsetParent of element3 is null even though element3 itself is visible, and parent is visible.

I've seen thin is Firefox 3.6 and Chrome 5. It seems to also affect the getBoundingClientRect() function on the element3, which is really annoying since that works in so many other cases!

Norman
A: 

https://developer.mozilla.org/en/DOM/element.offsetParent

offsetParent returns null when the element has style.display set to "none".

Ivan Kruchkoff