IE 6/7 - "Unspecified Error" when accessing offsetParent (Javascript)
I have noticed that IE 6/7 throws an "Unspecified Error"
exception when it attempts to get the offsetParent
property of a DOM object after the DOM tree has
been modified. Here is a repro. Remove the space in
java script
before viewing the page:
<html>
<head>
<script type="text/javascript">
var myInnerContentDiv;
function DisplayOffsetParent() {
try {
alert("offsetParent is " + myInnerContentDiv.offsetParent);
}
catch (e) {
alert(e.description );
}
}
function InjectContent() {
document.getElementById("myContent").innerHTML =
'div id: myContent<div id="myInnerContent" style=border: 1px solid #FF0000;>div id: myInnerContent</div> ';
}
function Init() {
myInnerContentDiv = document.getElementById("myInnerContent");
}
window.onload = Init;
</script>
</head>
<body>
1)<a href="java script:DisplayOffsetParent()">Display offsetParent</a><br />
2)<a href="java script:InjectContent();DisplayOffsetParent()">Inject content and display offsetParent</a>
<hr/>
<div id="myContent" style="border: 1px solid #0000FF;">
div id: myContent
<div id="myInnerContent" style="border: 1px solid #FF0000;">
div id: myInnerContent
</div>
</div>
</body>
</html>
The page has two div tags - "myContent" and
"myInnerContent", one nested in the other.
When the page loads, we obtain a reference to the
object with id "myInnerContent" and store it in a
global variable.
The first link calls a function that displays the
offsetParent of "myInnerContent” (we see that it is of
type object). The second link calls a function
that sets the innerHTML of “myContent” with some data and
then tries to get the offsetParent property of
"myInnerContent”.
If you are running in IE, you should see "Unspecified Error" when you click on the second link. Firefox on the other hand returns null.
You may run into this issue when you need to
store a reference to an object – especially when working
with AJAX.
To workaround this, you can store the id of the
object in a variable rather than a reference to the
object. Like so:
//a property of some object
var myInnerContentDivId;
function DisplayOffsetParent() {
alert("offsetParent is " + document.getElementById(myInnerContentDivId).offsetParent);
}
function Init() {
myInnerContentDivId = "myInnerContent";
}
Comments anyone?