views:

309

answers:

4

I can't figure out why document.getElementById is not working in Firefox:

document.getElementById("main").style.width = "100";

When I check in Firebug it says:

TypeError: document.getElementById("main") is null

Does anybody know why this is happening?

EDIT: Unfortunately, the "body" element was a bad example. I changed it to another element with an id of "main".

+3  A: 

Did you set the id of the <body> element to "body":

<body id="body" ...>

Update:

Check if the following example works for you: http://jsbin.com/uyeca/edit Click the Output tab to see the result (which should be a DIV with width 600px).

M4N
thanks, i just noticed that body was a bad example, and set it to a different id.
chris
thanks for noticing I didn't add "px"! (See comments above)
chris
+1 for jsbin link
hasen j
A: 

maybe it do not exists at the moment, when script executes, try to wait while document ready.

Anatoliy
A: 

https://developer.mozilla.org/En/DOM/Document.getElementById

Simply creating an element and assigning an ID will not make the element accessible by getElementById. Instead one needs to insert the element first into the document tree with insertBefore or a similar method, probably into a hidden div.

var element = document.createElement("div");
element.id = 'testqq';
var el = document.getElementById('testqq'); //

el will be null!

UncleO
A: 

Hello,

I had the same prob...I was trying to use "getElementById" without the main structure of the HTML page-- tag was missing.

After adding in my page it worked fine...I was working on a script that was supposed to be embeded on other sites--widget sort of thing.

Argyris