简体   繁体   中英

Why is document.getelementbyId not working in Firefox?

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".

put your script before

</body>

Or, if you use your script in <head> you may change code:

$(document).ready(function() {
    //enter code here.
});

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).

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM