javascript getElementById 在节点上不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3902671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementById doesn't work on a node
提问by Ursus Russus
In this simple script i get the error "obj.parentNode.getElementById is not a function", and I have no idea, what is wrong.
在这个简单的脚本中,我收到错误“obj.parentNode.getElementById 不是函数”,我不知道出了什么问题。
<script type="text/javascript">
function dosomething (obj) {
sibling=obj.parentNode.getElementById("2");
alert(sibling.getAttribute("attr"));
}
</script>
<body>
<div>
<a id="1" onclick="dosomething(this)">1</a>
<a id="2" attr="some attribute">2</a>
</div>
</body>
回答by Nick Craver
.getElementById()is on document, like this:
.getElementById()是document这样的:
document.getElementById("2");
Since IDs are supposed to be unique, there's no need for a method that finds an element by ID relative to any other element (in this case, inside that parent). Also, they shouldn't start with a number if using HTML4, a numberic ID isvalid in HTML5.
由于 ID应该是 unique,因此不需要通过相对于任何其他元素(在这种情况下,在该父元素内)的 ID 查找元素的方法。此外,如果使用 HTML4,它们不应该以数字开头,数字 ID在 HTML5 中是有效的。
回答by kernowcode
replace .getElementById(id) with .querySelector('#'+id);
用 .querySelector('#'+id) 替换 .getElementById(id);
回答by Kevin Seifert
document.getElementById()won't work if the node was created on the fly and not yet attached into the main document dom.
document.getElementById()如果节点是动态创建的并且尚未附加到主文档 dom 中,则将无法工作。
For example with Ajax, not all nodes are attached at any given point. In this case, you'd either need to explicitly track a handle to each node (generally best for performance), or use something like this to look the objects back up:
例如,对于 Ajax,并非所有节点都附加在任何给定点。在这种情况下,您需要显式跟踪每个节点的句柄(通常最适合性能),或者使用类似的方法来查找对象:
function domGet( id , rootNode ) {
if ( !id ) return null;
if ( rootNode === undefined ) {
// rel to doc base
var o = document.getElementById( id );
return o;
} else {
// rel to current node
var nodes = [];
nodes.push(rootNode);
while ( nodes && nodes.length > 0 ) {
var children = [];
for ( var i = 0; i<nodes.length; i++ ) {
var node = nodes[i];
if ( node && node['id'] !== undefined ) {
if ( node.id == id ) {
return node; // found!
}
}
// else keep searching
var childNodes = node.childNodes;
if ( childNodes && childNodes.length > 0 ) {
for ( var j = 0 ; j < childNodes.length; j++ ) {
children.push( childNodes[j] );
}
}
}
nodes = children;
}
// nothing found
return null;
}
}

