Wednesday, March 16, 2011

IE6 can't find Object element with getElementById()?

I'm trying to get an object element from my webpage using getElementById (ultimately so I can replace it with a dynamically created object element) but it is returning null in IE6.

In the following code, the byId() function returns null in IE but an [object HTMLObjectElement] in Firefox 3 and the lengthOfByTagName() function returns 0 in IE but 1 in Firefox.

Is there something I am doing wrong?

<html>
<head>
<title>IE doesn't see Object element?</title>
<script type="text/javascript">
function byId()
{
    var video = document.getElementById("VideoPlayer");
    alert(video);

}
function lengthOfByTagName()
{
    var length = document.getElementsByTagName("object").length;
    alert(length);

}
</script>

</head>
<body>
    <object type="" id="VideoPlayer">
     <param name="allowScriptAcess" value="always" />
     <param name="allowfullscreen" value="true" />
     VideoPlayer element
    </object>
    <br>
    <br>
    <a href="#" onclick="javascript:byId()">getElementById("VideoPlayer")</a>
    <br>
    <a href="#" onclick="javascript:lengthOfByTagName()">getElementsByTagName("object").length</a>
</body>
</html>
From stackoverflow
  • This is because of the way IE treats <object> nodes vis-a-vis the DOM.

    Since you're dynamically replacing anyway I recommend you instead create a <div> where you need it and change the innerHTML to be the HTML for the object you require.

    Albert : Thanks! Sometimes I forget that backing up and approaching in a different way can be the best thing to do.
  • I've just tested on IE 7 and seen the behavior as described

    Internet Explorer doesn't expect free text in an <object> tag. Using Debugbar on you sample prooved that IE doesn't build the right DOM tree.

    Use this code instead

    <object type="" id="VideoPlayer">
        <param name="allowScriptAcess" value="always" />
        <param name="allowfullscreen" value="true" />
    </object>
    

    It will work as expected.

    Albert : Thank you for your reply. Removing the free text does indeed fix the problem, but I thought that it was the correct way to provide fall-back content if the browser does not understand how to display the object element. For instance if a user does not have Flash installed.

0 comments:

Post a Comment