问题描述
如果你使用 getElementById
来处理像 - document.getElementById
这样的文档,那么它总是有效的.
If you use getElementById
to with document like - document.getElementById
then it always works.
但是,如果我们在一个元素上执行相同的操作,比如 x
,比如 x.getElementById
,那么它会返回一个错误.
But however, if we perform the same on an element say x
like x.getElementById
, then it returns an error.
不寻常的是 getElementsByClassName
和 getElementsByTagName
对元素起作用,而 getElementById
不起作用!
The unusual thing about this is that getElementsByClassName
and getElementsByTagName
work on the elements however getElementById
doesn't!
推荐答案
容器 ID 应该是唯一的,因此没有理由在另一个容器中通过 ID 查找对象.这就是为什么您只需要 document.getElementById
来通过其 ID 访问任何元素,而当您按类或标签名称搜索时,您可能只想在特定容器内搜索,这就是为什么您可以做 x.getElementsByClassName
等
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.
这篇关于为什么 getElementById 对文档元素内的元素不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!