views:

90

answers:

5

I have the following javascript code

var myDiv = document.getElementById("myDiv");
alert(myDiv);                
myDiv.style.display = 'none';

the call to alert(myDiv) succesfully shows that myDiv is not null and I see that the object (the div) has all the necessary properties set etc.

However, the call to myDiv.style.display = none results in an Object Required javascript error in IE 8.

Any pointers on what I need to check?

Thanks.

A: 

Works for me in IE8

Drew
+2  A: 

Make sure your html markup is valid. You can use validation service provided by w3c. Or if you are using any IDE check if it has validation facility

Xinus
I double checked, and double checked, and double checked and you were right, I had a typo that was causing the problem.Thanks :)
Hovito
Most of the times if simple JavaScript DOM fails.. markup is the problem :-)
Xinus
+1  A: 

Make sure this script is called at window.onload, not before.

Edit: also, make sure you avoid the common pitfall of doing this:

window.onload = foo() # PROBABLY WRONG

When really you wanted to do this:

window.onload = foo
Ben James
Hi, well I'm calling it at body.onload but I'll try your suggestion and report back.
Hovito
A: 

Also, check that besides only attempting this after the DOM has loaded, that you don't have more than one element on the page with the same myDiv ID. View Source and try to find where this appears, make sure it isn't accidentally repeated.

Good luck!

Funka
A: 

An html element will/can have id and name. In my application we use master pages (asp.net) so when you place a control under a content page which is derived by master page,

the id of the control will be like "ctl00_ctl00_ctlname"

and

the name will have "ctl00$ctl00$ctlname"

Now, if getElementById works fine in IE7(IE 7) and not in IE8(IE 8) then one possible reason is the value / attribute passed in getElementById method. This is because IE7 used to find control by name if the id does not match.

In short if you are passing the value of name attribute then the getElementById() will not work in IE8

happy coding :)

Baljeetsingh