IE6 can't find Object element with getElementById()?
-
22-07-2019 - |
Question
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>
Solution
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.
OTHER TIPS
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.
In IE6, it may not work. For refer: https://msdn.microsoft.com/en-us/library/ie/ms536437%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396magazine
Suggest using jQuery to handle most of the cases
jQuery
var video = $("#VideoPlayer");
alert(video);
Try this in your coding.