节点类型 上

80 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

DOM API中有两个非常重要的对象,一个是 Node, 一个是 Element

Element其实一种特殊的Node,Node有一个属性为nodeType, nodeType值为1的就是Element。

Node和Element各自提供了很多操作节点的能力,平时我们也不会太区分。

比如:

  • classList, clientWidth, getAttribute等等都是Element提供的。
  • nodeType, cloneNode, appendChild等等都是Node提供的。

其实也不用特别记忆,

  1. 和显示有关的,比如classList, clientWidth等
  2. 属性名带Element的,比如getElementsByTagName, firstElementChild等
  3. 和attribute相关的, getAttribute等
  4. 和节点查找先关的,querySelector等

基本都是Element提供的,基本都是Element提供的,例外,比如 Node.parentElement

Node只提供了基本的属性和方法。

节点类型概览

12种节点类型,引用www.w3school.com.cn/jsref/prop_…

节点类型值节点类型描述子节点
1Element代表元素Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
2Attr代表属性Text, EntityReference
3Text代表元素或属性中的文本内容。None
4CDATASection代表文档中的 CDATA 部分(不会由解析器解析的文本)。None
5EntityReference代表实体引用。Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
6Entity代表实体。Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
7ProcessingInstruction代表处理指令。None
8Comment代表注释。None
9Document代表整个文档(DOM 树的根节点)。Element, ProcessingInstruction, Comment, DocumentType
10DocumentType向为文档定义的实体提供接口None
11DocumentFragment代表轻量级的 Document 对象,能够容纳文档的某个部分Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
12Notation代表 DTD 中声明的符号。None

其中2,5,6,12还过时了,所以基本有意思的就是8种了。

Element(1)

nodeType值为1,我们常用的div, a, span, section, table, header等等都是。 使我们日常操作最多的节点类型。

Text(3)

文本节点,我们直接写的文字或者字母,其实最后都转为文本节点。

<div id="root">123  
    456
    789
</div>

image.png

可以看到实际上你以为是纯文本,其实不然。

再看一个熟悉的概念,空白节点。

    <div id="parent">
      <div class="child"></div>
    </div>

    <script>
      console.log("parent.childNodes", document.getElementById("parent").childNodes);
    </script>

image.png
div的前后都有白的Text节点。

DOCUMENT_NODE (9)

文档节点, document就是这个玩意的实例。

document.nodeType
// 9

再看看document包含哪些东西:

image.png

没错整个我们编写的页面就是document。

小结

今天我们介绍了节点类型,和最常见的三种节点类型。

今天你收获了吗?