怎样理解HTMLCollection接口

和 NodeList 类似, HTMLCollection 也是一个 类数组对象, 和NodeList不同的是, 它是各种 元素节点 的集合, 且不具有 forEach() 方法, 因此如果不转为真正的数组, 则只能用 for 去遍历.

会返回 HTMLCollection 对象的属性方法包括: document.links / document.forms / document.images / document.getElementsByXXX() / 等, 在实际开发中, 碰到HTMLCollection 的概率会比 NodeList 要更多.

document.getElementsByTagName('div') instanceof HTMLCollection
// true

document.querySelectorAll('div') instanceof NodeList
// true

以上两个方法获取页面上所有 div 元素节点, 不过前者(document.getElementsByTagName)要更快, 因为它只在元素节点里面找, 而后者是在7种节点类型里面找.

猜你喜欢

转载自www.cnblogs.com/aisowe/p/11526904.html