getElementsByClassName 和 querySelectorAll 区别

306 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情

背景

今天,是复习的一天。突然想到了 getElementsByClassName和querySelectorAll区别这一老问题?决定写出来,首先,增强下记忆。其次,希望帮助目前还不能分清的伙伴。

getElementsByClassName 说明

在使用上,这两个API都是document上的方法。都可以通过className去获取页面上的元素。getElementsByTagName返回一个包含了所有指定类名的元素的类数组。也可以说返回一个HTMLCollection元素集合。使用语法如下:

const elements = document.getElementsByClassName('your-class-name')

querySelectorAll 说明

querySelectorAll虽然也是document上的方法,但是返回的集合是nodeList,也就是节点集合。但是其相对语法上较前者有一点差异。例如:仍然拿查找类名是'your-class-name'的元素集合为例。这里需要使用。来告诉querySelectorAll要找的是类,因为这个属性能力更大些,也可以查找id等其他的节点集合。使用语法如下:

cosnt elementst = document.querySelectorAll('.your-class-name');

HTMLCollection 说明

上面提到HtmlCollection是getElementsByClassName的返回集合。其实他还是动态集合,相当于获取了真实元素的引用,当页面变更后,获得的变量也会跟着页面内容变化。

NodeList 说明

NodeList是querySelectorAll的返回集合,同时它是一个静态集合。通俗点说相当于它是一个快照集合。也就是不会随着页面元素的变化而变化。感觉起来对增删不敏感,但要注意的是,插入也就是innerHTML会一同变更。

代码说明

    const htmlCollection = document.getElementsByClassName('your-class-name')[0];
    const nodeList =  document.querySelectorAll('.your-class-name')[0];
    
    const htmlCollectionLi = document.getElementsByTagName('li')
    const nodeListLi = document.querySelectorAll('li')
    
    const li = document.createElement('li');
    htmlCollection.appendChild(newLi);

    console.log(htmlCollectionLi);
    console.log(nodeListLi);

通过上面这几行代码,再配上控制台输出的li数量,就能看出来两者的静态关系了。

收获和总结

最后,总结一下,方便大家好记忆:

  1. getElementsByClassName返回的是HTMLCollection,元素的动态集合。
  2. querySelectorAll返回的是NodeList,节点的静态集合。