View Full Version : Error in IE8: Message: 'document.getElementById(...)' is null or not an object

Nov 23rd, 2009, 09:00 PM
Hi, first post here. I was working on code for opening a link in a new window when clicked. I read somewhere that it's a good idea to remove all of the javascript elements from the HTML. So I pieced it together and it works. But I get the following error in IE8:

Message: 'document.getElementById(...)' is null or not an object

Here's the relevant HTML:

<a href="http://www.samplesite.com" id="sampleid">Sample Text</a>

And here's the relevant javascript that I put in a seperate .js file:

function samplefct() {
window.open(this.href);return false;

window.onload = function()
{document.getElementById("sampleid").onclick = samplefct;

The code does work as planned. But I'd still like to get rid of the error. Can anybody think of a different way of stating the javascript that would perform the same thing and lose the error?

Any help would be greatly appreciated.

Old Pedant
Nov 23rd, 2009, 09:28 PM
Only thing I can think of is that maybe you have two objects with that same id on the page???

Can you show it live?

And not to ask a silly question, but why not get rid of all the JS code and just do:

<a href="http://www.samplesite.com" target="_new">Sample Text</a>

Nov 24th, 2009, 12:08 AM
Thanks Old Penant. I think you might be on the right track. I don't have two objects with the same ID. But I tried isolating things, creating a new HTML page and a new .js file with only the code in question. I don't get the error now in IE. So there's something on my pages interacting and causing the error. I'll just have to go thru and keep narrowing it down until I isolate the problem.

I read about the target="new" option and thought about it. I'm not worried about it not validating with Strict XHTML. But I decided I didn't want to force a window on users that have js turned off on purpose. The 'open new window' link goes to a shipping option description page, coming from a Miva shopping cart page towards the end of the order process. That's why I have it open in a new window. Name and address info is already filled out, so I don't want the user to get lost and end up having to re-enter that info. For people that go out of their way to turn js off, I don't want to tick them off by opening a new window. Probably not a big deal. I could go either way with it really.

Thanks for the help!

Old Pedant
Nov 24th, 2009, 03:35 AM
Oh, I got you. So if they have JS turned off, you just let them end up with the page in their main window instead. Makes lots of sense. Will remember that one.