Wednesday, July 2, 2008

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:

    DOM Element offsetParent test


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.
The following piece of code:
 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.

No comments:

Post a Comment