为什么如果我只有一个h1
文档中的元素,我还必须使用索引来访问吗?
就像下面这样不行。
document.getElementsByTagName('h1').innerHTML = "SHUSHAN";
但如果我这样做
document.getElementsByTagName('h1')[0].innerHTML = "SHUSHAN";
它确实有效。
虽然我只有一个h1
,为什么我必须指定?
简短的回答:这是为了让你保持理智。
如果您不知道是否会获得单个元素或元素集合,则必须编写像这样的防御性类型检查(愚蠢)代码
let foo = document.getElementsByTagName('h1')
if (foo instanceof HTMLCollection)
// do something with all elements
else
// do something with just one element
对于函数来说,总是返回一个已知类型更有意义,HTMLCollection
of HTMLElement
objects
如果您只关心获取第一个元素,则可以使用解构赋值
let [first] = document.getElementsByTagName('h1')
console.log(first) // outputs just the first h1
这很好,因为赋值清楚地表明它需要一个元素数组(或类似数组),但只关心将标识符分配给第一个值
您还应该了解较新的document.querySelector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector and document.querySelectorAll https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll功能 …
这是我在 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)