为什么getElementById不能在文档元素内的元素上工作? [英] Why does getElementById not work on elements inside the document element?

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

问题描述

如果您使用 getElementById 与 - document.getElementById 之类的文档一起工作。但是,如果我们对 x x这样的元素执行相同的操作。 getElementById ,则返回一个错误。



这个不寻常的事情是 getElementsByClassName getElementsByTagName

解决方案

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


If you use getElementById to with document like - document.getElementById then it always works.

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

The unusual thing about this is that getElementsByClassName and getElementsByTagName work on the elements however getElementById doesn't!

解决方案

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天全站免登陆