为什么 getElementById 对文档元素内的元素不起作用? [英] Why does getElementById not work on elements inside the document element?

查看:35
本文介绍了为什么 getElementById 对文档元素内的元素不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你使用 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.

不寻常的是 getElementsByClassNamegetElementsByTagName 对元素起作用,而 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 对文档元素内的元素不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆