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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:16:10  来源:igfitidea点击:

Why does getElementById not work on elements inside the document element?

javascripthtmldom

提问by akash4eva

If you use getElementByIdto with document like - document.getElementByIdthen it always works.

如果您习惯于使用getElementById文档之类的 -document.getElementById那么它始终有效。

But however, if we perform the same on an element say xlike x.getElementById, then it returns an error.

但是,如果我们在元素上执行相同的操作,比如xlike x.getElementById,那么它会返回一个错误。

The unusual thing about this is that getElementsByClassNameand getElementsByTagNamework on the elements however getElementByIddoesn't!

关于这个不寻常的是,getElementsByClassNamegetElementsByTagName上的元素但工作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.getElementByIdto 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.getElementsByClassNameetc.

容器 ID 应该是唯一的,因此没有理由在另一个容器中按 ID 查找对象。这就是为什么您只需要document.getElementById通过其 ID 访问任何元素,而当您按类或标签名称搜索时,您可能只想在特定容器内搜索,这就是为什么您可以这样做的原因x.getElementsByClassName