IE quirk: offsetParent of DOM element added into document.body
We spent about 1 day of work while find out the following crazy feature of DOM implementation in Internet Explorer.
Just look at the HTML page below and try to say what will be shown on execution of the test() JavaScript function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<head>
<title>DOM Element offsetParent test</title>
</head>
<body>
<script type="text/javascript">
function test() {
var element = document.createElement("div");
element.style.position = "absolute";
document.body.appendChild(element);
window.alert(element.offsetParent.nodeName);
}
</script>
<a href="#" onclick="test();">Test</a>
</body>
</html>
You think it will show you "BODY" text?
You will be right in case of FireFox or Opera. But in Internet Explorer (we tested it both on versions 6 and 7) test() function will print "HTML" instead of "BODY" because element.offsetParent in this case is equal to document.documentElement instead of document.body as you may suppose.
Why is it implemented in such strage way? I do not know.
Moreover, for some reason it works right (shows "BODY" text) if you change the DTD declaration for this page to the following:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"">
So just be careful when implementing such functions as described in this post.
Actually we had to make changes in our existing code when found this strange behaviour, for example in our GetElementAbsolutePos() function.
if (offsetParent != document.body) {
res.x -= offsetParent.scrollLeft;
res.y -= offsetParent.scrollTop;
}
had been changed to this one:
if (offsetParent != document.body && offsetParent != document.documentElement) {
res.x -= offsetParent.scrollLeft;
res.y -= offsetParent.scrollTop;
}
Hope this information will save somebody's time. Enjoy!
Re: IE quirk: offsetParent of DOM element added into document.body
I found another solution for this problem.
You can use XHTML Transitional - if you set the position css-element for the body tag.
body
{
position : absolute;
}
I test all 4 posible "position" settings:
position: static; -> offset find "HTML"
position: fixed; -> offset find "HTML"
position: absolute; -> offset find "BODY"
position: relativ; -> offset find "BODY"
Re: IE quirk: offsetParent of DOM element added into document.body
It can be good solution if you work on your own web-site when you can control the style for any page but unfortunately it can not be applied in case of somebody else's web-site where you can not control the content and styles.

