Html 为什么 getElementById 对文档元素内的元素不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16475636/
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
Why does getElementById not work on elements inside the document element?
提问by akash4eva
If you use getElementById
to with document like - document.getElementById
then it always works.
如果您习惯于使用getElementById
文档之类的 -document.getElementById
那么它始终有效。
But however, if we perform the same on an element say x
like x.getElementById
, then it returns an error.
但是,如果我们在元素上执行相同的操作,比如x
like x.getElementById
,那么它会返回一个错误。
The unusual thing about this is that getElementsByClassName
and getElementsByTagName
work on the elements however getElementById
doesn't!
关于这个不寻常的是,getElementsByClassName
和getElementsByTagName
上的元素但工作getElementById
不!
回答by mash
Container IDs should be unique, so there's no reason to find an object by ID within another container. This is why you only need document.getElementById
to access any element by its ID, whereas when you are searching by class or tag name, you might want to only search within a specific container, which is why you can do x.getElementsByClassName
etc.
容器 ID 应该是唯一的,因此没有理由在另一个容器中按 ID 查找对象。这就是为什么您只需要document.getElementById
通过其 ID 访问任何元素,而当您按类或标签名称搜索时,您可能只想在特定容器内搜索,这就是为什么您可以这样做的原因x.getElementsByClassName
。