Hye*_*sho 3 javascript dom getelementsbytagname
为什么如果我h1在文档中只有一个元素,我仍然需要使用索引来访问它?
喜欢以下不起作用.
document.getElementsByTagName('h1').innerHTML = "SHUSHAN";
Run Code Online (Sandbox Code Playgroud)
但如果我这样做
document.getElementsByTagName('h1')[0].innerHTML = "SHUSHAN";
Run Code Online (Sandbox Code Playgroud)
它确实有效.
即使我只有一个h1,为什么我必须指定?
简短回答:这样你就可以有一些理智.
如果您不知道是否会获得单个元素或元素集合,则必须编写防御性类型检查(愚蠢)代码,如下所示
let foo = document.getElementsByTagName('h1')
if (foo instanceof HTMLCollection)
// do something with all elements
else
// do something with just one element
Run Code Online (Sandbox Code Playgroud)
使函数始终返回已知类型HTMLCollection的HTMLElement对象更有意义
如果您只关心获取第一个元素,则可以使用解构赋值
let [first] = document.getElementsByTagName('h1')
console.log(first) // outputs just the first h1
Run Code Online (Sandbox Code Playgroud)
这很好,因为赋值清楚地表明它期望一个数组(或类似数组)的元素,但只关心为第一个值分配一个标识符
您还应该了解更新document.querySelector和document.querySelectorAll功能......
document.querySelector将从文档中选择最多 一个元素或返回null
document.querySelectorAll将始终返回一个HTMLCollection,但如果没有元素与选择器匹配,则可能为空.
以下是我2017年编写代码的方法
setTimeout($ => {
// get the element to change
let elem = document.querySelector('h1')
// update the text of the element
elem.textContent = 'SHUSHAN'
}, 3000)Run Code Online (Sandbox Code Playgroud)
<h1>wait 3 seconds ...</h1>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
914 次 |
| 最近记录: |