有关每种方法的详细信息是否有效,但似乎没有确定它的标准约定。
document.getElementsByClassName()是HTMLCollection,并且是活的。
document.getElementsByTagName()是HTMLCollection,并且是活的。
document.getElementsByName()是一个NodeList并且是活的。
document.querySelectorAll()是一个NodeList并且不是活的。
HTMLCollections 似乎总是活着
HTMLCollection 是一个节点列表。可以通过序数索引或节点的名称或 id 属性访问单个节点。
注意:HTML DOM 中的集合被假定为活动的,这意味着它们会在底层文档更改时自动更新。
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506
所以,HTML 集合总是“在 dom 中”,而 anodeList是一个更通用的构造,可能在也可能不在 DOM 中。
NodeList 对象是节点的集合... NodeList 接口提供了节点有序集合的抽象,而不定义或限制如何实现该集合。DOM 中的 NodeList 对象是活动的。
http://www.w3.org/TR/DOM-Level-3-Core/core.html#td-live
听起来不错,对吧?
集合是表示 DOM 节点列表的对象。集合可以是实时的,也可以是静态的。除非另有说明,否则集合必须是实时的。
http://www.w3.org/TR/2012/WD-dom-20120405/#collections
因此,静态集合将在规范中如此指示。所以,按照这个逻辑,document.querySelectorAll()是一个集合,但它不在DOM 中。因为虽然集合可能会或可能不会住,收藏在DOM中必须是活的......这种区别是不是超级有用的。
好吧,这里有一个快速的方法来确定 acollection是否存在;它将集合成员的克隆附加到DOM(因此它将匹配选择器),并检查长度是否发生变化,然后将其删除(因此页面不受影响)
演示
function isLive(collection) {
    if (HTMLCollection.prototype.isPrototypeOf(collection)) return true // HTMLCollections are always live
    const length = collection.length;
    if (!length) return undefined; // Inconclusive
    const el = collection.item(0);
    const parent = el.parentNode;
    const clone = el.cloneNode();
    clone.style.setProperty('display', 'none', 'important');
    parent.appendChild(clone);
    const live = collection.length !== length;
    parent.removeChild(clone);
    return live;
}
const divs1 = document.getElementsByClassName('c');
const divs2 = document.getElementsByTagName('span');
const divs3 = document.getElementsByName('notFound');
const divs4 = document.querySelectorAll('.c');
console.log("document.getElementsByClassName('c'):", divs1.toString()); //   [object HTMLCollection]
console.log("document.getElementsByTagName('notFound'):", divs2.toString()); //  [object HTMLCollection]
console.log("document.getElementsByName('notFound'):", divs3.toString()); // [object NodeList]
console.log("document.querySelectorAll('.c'):", divs4.toString()); //        [object NodeList]
console.log('isLive(divs1)', isLive(divs1)); // true
console.log('isLive(divs2)', isLive(divs2)); // true
console.log('isLive(divs3)', isLive(divs3)); // undefined
console.log('isLive(divs4)', isLive(divs4)); // false
<html>
    <body>
        <div>
            <div class="c">C1</div>
            <div class="c">C2</div>
        </div>
        <div>
            <div class="c">C3</div>
            <div class="c">C4</div>
        </div>
    </body>
</html>