javascript 使用 getElementsByTagName 获取单个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6772962/
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-10-25 21:48:51  来源:igfitidea点击:

Getting a single element with `getElementsByTagName`

javascripthtmldomgetelementsbytagname

提问by Jamna

I know that if we want to find a group of elements, getElementsByTagName is the method for us and it returns a NodeList. but if we are looking for tag name with "body" , then why we need to add [0] after the ("body") element? There is only one body tag in an HTML document.

我知道如果我们想找到一组元素,getElementsByTagName 是我们的方法,它返回一个 NodeList。但是如果我们正在寻找带有 "body" 的标签名称,那么为什么我们需要在 ("body") 元素之后添加 [0] 呢?HTML 文档中只有一个 body 标签。

 var body = document.getElementsByTagName("body")[0];
 body.className = "unreadable";

why we cant write this code without index[0] like this

为什么我们不能像这样在没有 index[0] 的情况下编写这段代码

 var body = document.getElementsByTagName("body");
 body.className = "unreadable";

If i write this code the class unreadable will not be added with body tag ...why?

如果我写了这段代码,那么不可读的类将不会添加 body 标签......为什么?

回答by Molecular Man

Because document.getElementsByTagNameallways returns NodeList. If you want find easier way to retrieve body you can use just document.body

因为document.getElementsByTagName总是返回 NodeList。如果你想找到更简单的方法来检索身体,你可以只使用document.body

回答by Quentin

getElementsByTagNamereturns a NodeList. It might have no items in it. It might have one. It might have many. You can see how many are in it by testing its .length.

getElementsByTagName返回一个节点列表。它可能没有项目。它可能有一个。它可能有很多。您可以通过测试其.length.

It would be confusing if it sometimes returned a NodeList and sometimes returned an ElementNode.

如果它有时返回一个 NodeList 而有时返回一个 ElementNode,那将会令人困惑。

回答by Felix Kling

getElementsByTagName[docs]alwaysreturns a NodeList. It does not matter whether an element with a certain tag exists only once.

getElementsByTagName[文档]总是返回一个NodeList. 带有某个标签的元素是否只存在一次并不重要。

It would be bad if the function behaved inconsistently.

如果函数的行为不一致,那就不好了。