DOM中的node与element的区别

先看document的两个常见method。

  • document.createTextNode
    • Constructor: Text
  • document.createElement
    • Constructor: HTML*Element

此处涉及三个DOM API: Text, Node, Element。其关系可参考下图。

由此可见, Node包括Document, Element, CharacterData(Parent of Text, Comment, etc.).

再看看element的两个常见method。

  • element.children
    •   返回HTMLCollection
  • element.childNodes
    •   返回NodeList

children只返回element,childNodes返回所有node. 一般来说,children.length<=childNodes.length.

例子。

Test HTML

<div id="p">Hello<div id="c">DOM API</div><!--I am a comment--></div>

Test Browser: Chrome

var p = document.getElementById('p');
console.log(p.childNodes);
console.log(p.children);

结果

注:另外相关的element的method还有parentNode和parentElement。区别同上。例如, document.children[0].parentNode是HTMLDocument, 而document.children[0].parentElement是null. 因为document是Node,但不是Element。(document.children[0]是HTMLHtmlElement, document.children.length===1.)

Wisdom dawns when names and forms vanish.
原文地址:https://www.cnblogs.com/gentlemint/p/5476742.html