2009-09-24 35 views
2

我想不通为什么的document.getElementById没有在Firefox工作:为什么document.getelementbyId在Firefox中不起作用?

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

当我在Firebug检查它说:

类型错误:的document.getElementById( “主”)为空

有人知道为什么会发生这种情况吗?

编辑:不幸的是,“身体”元素是一个坏榜样。我将其更改为ID为“main”的另一个元素。

+0

对不起,坏榜样;我将问题改为具有ID的实际元素。 – chris 2009-09-24 18:49:49

+0

你在某处重新定义了document.getElementById还是加载了一些JS?在萤火虫中适用于我。 – seth 2009-09-24 18:55:08

+4

我们来看看你的html。 – 2009-09-24 18:56:19

回答

3

你有没有设置<body>元素,以“身体”的ID:

<body id="body" ...> 

更新:

检查下面的例子为你工作:http://jsbin.com/uyeca/edit 单击输出标签来查看结果(它应该是宽度为600px的DIV)。

+0

谢谢,我只是注意到身体是一个不好的例子,并将其设置为不同的ID。 – chris 2009-09-24 18:51:05

+0

感谢您注意我没有添加“px”! (请参阅上面的注释) – chris 2009-09-24 19:10:35

+0

+1用于jsbin链接 – hasen 2009-09-25 02:21:12

3

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!

0

我有相同的概率...我试图用“的getElementById”没有HTML page--标签的主体结构失踪。

加入我的页面后,它工作正常......我正在研究一个本应嵌入在其他网站上的脚本 - 小部件排序的事情。

4

把你的脚本

</body> 

之前或者,如果您在使用<head>脚本您可以更改代码:

$(document).ready(function() { 
    //enter code here. 
}); 
相关问题