I call this function with two elements having the same parentNode
:
var test = function(target, div){
alert(div.parentNode == target.parentNode ); // gives true
alert(div.offsetParent == target.offsetParent); // gives true
div.setAttribute("style", "position:relative; float:left; height:" + target.offsetHeight + "px;");
alert(div.parentNode == target.parentNode); // gives true
alert(div.offsetParent == target.offsetParent); // gives false!!!
}
As you can see that both elements have same parent, which means they are inside same branch of the DOM tree, how come they have different offsetParent
?
I notice here that div has relative position, which seems to be the reason because when I remove it both alerts give true. (but normally the position of an element should not affect its offsetParent
)
/* I have edited the function after some more invistigation it should show more where lies the problem */ I got the same results on FF and Chrome. parentNode of both elements is a table-td
Thank you for answering.
Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.
The offset parent is the nearest ancestor that has a position other than static. If no offset parent exists, the offset parent is the document body.
jQuery offsetParent() MethodThe offsetParent() method returns the first positioned parent element. Tip: An element can be positioned with jQuery, or with the CSS position property (relative, absolute, or fixed).
offsetParent() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object wrapped around the closest positioned ancestor. An element is said to be positioned if it has a CSS position attribute of relative , absolute , or fixed .
Just because both properties contain the word "parent" does not mean they are similar.
offsetParent
property returns the closest element in the ancestors hierarchy that is positioned.parentNode
property simply returns the immediate parent element.Now, if two elements are siblings (as in your example) then their offset parents should be same. However, it is possible for an element to return null
instead of offset parent, for example:
display: none
position: fixed
Edit: your example involves a td
element so the offset parent is calculated in a weird manner. Inside a td
element:
td
element as their offset parent. This means target.offsetParent
will be that td
.div.offsetParent
will be body
since div is positioned.The simplest workaround to make both elements have same offset parent is to add position: relative
on the table cell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With