Node 和 Element 是什么关系?
参考答案
Element 是 Node 的子类型,二者是继承关系:Node → Element → HTMLElement → 具体元素类(如 HTMLDivElement)。
Node 覆盖的范围更大
nodeType 区分:1 Element、2 Attr、3 Text、4 CDATASection、7 ProcessingInstruction、8 Comment、9 Document、10 DocumentType、11 DocumentFragment。也就是说,文本、注释、文档、片段都是 Node,但不是 Element。
能力差异
Node通用:parentNode、childNodes、firstChild、nextSibling、appendChild、removeChild、replaceChild、cloneNode、contains、isEqualNode、nodeName、nodeValue、textContent、addEventListener。Element额外:tagName、id、className、classList、attributes、getAttribute/setAttribute、dataset、innerHTML、children、firstElementChild、querySelector(All)、getBoundingClientRect、matches、closest、样式相关。
实践区别
const box = document.querySelector('#box');
box.childNodes; // NodeList,可能含空白 Text 节点
box.children; // HTMLCollection,只有元素
box.firstChild; // 可能是 #text
box.firstElementChild; // 一定是元素
所以「遍历子元素」用 children,做通用 DOM 操作(文本、注释)才用 childNodes;instanceof Element / nodeType === 1 可判断是否为元素。注意 Attr 虽是 Node 却不在树中,且已不推荐用 attributes 的节点 API 操作属性。