为什么getElementsByTagName()总是返回一个数组? [英] Why do getElementsByTagName() always returns an array?

查看:191
本文介绍了为什么getElementsByTagName()总是返回一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么如果我在文档中只有一个 h1 元素,我仍然需要使用索引来访问它?

Why is it that if I have only one h1 element in the document, I still have to use the index to access it?

如下所示不起作用。

document.getElementsByTagName('h1').innerHTML = "SHUSHAN";

但如果我这样做

document.getElementsByTagName('h1')[0].innerHTML = "SHUSHAN";

确实有效。

尽管我只有一个 h1 ,为什么我必须指定?

Even though I only have one h1, why do I have to specify?

推荐答案

简答:这样你就可以有一些理智。

Short answer: This is so that you can have some sanity.

如果你不知道你是否会得到一个元素或一组元素,你会必须写这样的防御性,类型检查(愚蠢)代码

If you don't know whether you will get a single element or a collection of elements, you would have to write defensive, type-checking (stupid) code like this

let foo = document.getElementsByTagName('h1')
if (foo instanceof HTMLCollection)
  // do something with all elements
else
  // do something with just one element

让函数更有意义的是总是返回一个已知类型, HTMLCollection HTMLElement 对象

It makes way more sense for the function to always return a known type, an HTMLCollection of HTMLElement objects

如果你只关心获得第一个元素,你可以使用解构赋值

If you only care about getting the first element, you can use destructuring assignment

let [first] = document.getElementsByTagName('h1')
console.log(first) // outputs just the first h1

这很好,因为赋值清楚地表明它期望一个数组(或类数组)元素,但只关心为第一个值分配一个标识符

This is fine because the assignment clearly shows that it's expecting an array (or array-like) of elements but only cares about assigning an identifier to the first value

你还应该知道更新的 document.querySelector document.querySelectorAll functions…

You should also be aware of the newer document.querySelector and document.querySelectorAll functions …


  • document.querySelector 将从文档中选择最多 一个元素或返回 null

  • document.querySelector will select at most one element from the document or returnnull

document.querySelectorAll 将始终返回 HTMLCollection ,但如果没有元素与选择器匹配,则可能为空。

document.querySelectorAll will always return an HTMLCollection, but may be empty if no elements match the selector.

以下是我2017年编写代码的方法

Here's how I'd write your code in 2017

setTimeout($ => {
  // get the element to change
  let elem = document.querySelector('h1')
  // update the text of the element
  elem.textContent = 'SHUSHAN'
}, 3000)

<h1>wait 3 seconds ...</h1>

这篇关于为什么getElementsByTagName()总是返回一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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