My IE does not support "document.getElementById ()"!

My IE is IE 6. It's pretty old, but I have to use it.

I just found a strange problem, it does not support "document.getElementById ()"!

See my test file: test.html

<a id="aaa">xxx</a> <script> aaa = document.getElementById("aaa"); alert(aaa); </script> 

When I open this IE file, the ERROR dialog box appears:

 line: 3 char: 1 error: object doesn't support the attribute or method code: 0 URL: file://D:/test.html 

Did I make some mistakes? This is so weird ~

+7
javascript internet-explorer-6
source share
5 answers

This is because the binding element is configured (in IE6) as a global variable called aaa. And then you try to use another variable with the same name.

If you change it to ...

 <a id="aaa">xxx</a> <script> bbb = document.getElementById("aaa"); alert(bbb); </script> 

he should work.

See http://verens.com/2005/03/18/getelementbyid-bug-in-ie6/

+15
source share

Change the variable name so that it does not match the identifier of the element.

+4
source share

As noted by barrylloyd, its because the binding element is configured (in IE6) as a global variable named aaa. You can use var to create aaaa local variable:

 <a id="aaa">xxx</a> <script type="text/javascript"> var aaa = document.getElementById("aaa"); alert(aaa); </script> 
+4
source share

Is this a fragment of your html file or the whole file? In the first case, I would suggest adding the appropriate tags ( <html> , <body> ) and doctype. Secondly, the element must be loaded when doing this javascript, but with IE6 I would not rely on it. So you can try it inside the onload function:

 window.onLoad = function() { alert(document.getElementById("aaa")); } 
0
source share

It works if you put the javascript block in the section of the <head> . Where JS should usually be located anyway.

-3
source share

All Articles