getElementById returns null?
getElementById returns null?
document.getElementById('id of div that definately exists')
返回null。
我最初最后加载javascript是为了确保不必担心onload事件。我还尝试使用onload事件。非常恐怖。任何想法或帮助都将不胜感激。
还要注意如何在页面上执行js。例如,如果你做这样的事情:
(function(window, document, undefined) {
var foo = document.getElementById("foo");
console.log(foo);
})(window, document, undefined);
这将返回null,因为您将在加载文档之前调用该文档。
使用window.onload
等待dom节点加载:
(function(window, document, undefined) {
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
// #document has its nodes
}
})(window, document, undefined);
可能由以下原因引起:
- 无效的HTML语法(某些标记未关闭或类似错误)
- 重复的ID-有两个HTML DOM元素具有相同的ID
- 也许您试图通过ID获取的元素是动态创建的(通过ajax加载或通过脚本创建)
请张贴您的代码。
document.getElementById
不起作用的原因可能有很多
-
您的ID 无效
ID和NAME标记必须以字母([a-Za-z])开头,后面可以跟任意数量的字母、数字([0-9])、连字符("-")、下划线("_")、冒号(":")和句点(".")。(参考资料:HTML中id属性的有效值是什么?)
-
你在标题中使用了一些已经用作
<meta>
名称的id(例如版权、作者…),这看起来很奇怪,但我碰巧遇到了:如果你正在使用IE,请查看(资源:http://www.phpied.com/getelementbyid-description-in-ie/) -
你的目标是框架或iframe中的一个元素。在这种情况下,如果iframe在父级的同一域中加载了一个页面,则在查找元素之前,应该以
contentdocument
为目标(资源:调用帧内的特定id) -
当节点没有有效地加载到DOM中时,您只是在寻找一个元素,或者它可能是一个拼写错误的
我怀疑您是否使用了两次或两次以上相同的ID:在这种情况下,document.getElementById
应该至少返回第一个元素
- Firefox-SDK contentScript returns null
- document.getElementById(#mapid) returns null
- JavaScript getElementById returns null
- Javascript getElementByID for asp:Image returns null
- Magento newsletter ajax request returns null
- GetCookie returns NULL
- getElementByID returns null (jsfiddle inside)
- PowerShell getElementByTagName("a") returns NULL
- getElementbyID returns Null
- JavaScript/Node match returns null
- GetElementByID returns null value
- window.onload and getelementbyid returns null
- Angular Factory returns null
- jquery html returns null
- getElementById returns null?
- Postman PUT JSON Returns Null
- document.querySelector() returns null
- get_selectedItems()[0] on RadGrid returns null
- SVG getIntersectionList returns null
- getTargetEl().down('input') of textarea returns null