小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
DOM API中有两个非常重要的对象,一个是 Node, 一个是 Element。
Element其实一种特殊的Node,Node有一个属性为nodeType, nodeType值为1的就是Element。
Node和Element各自提供了很多操作节点的能力,平时我们也不会太区分。
比如:
- classList, clientWidth, getAttribute等等都是Element提供的。
- nodeType, cloneNode, appendChild等等都是Node提供的。
其实也不用特别记忆,
- 和显示有关的,比如classList, clientWidth等
- 属性名带Element的,比如getElementsByTagName, firstElementChild等
- 和attribute相关的, getAttribute等
- 和节点查找先关的,querySelector等
基本都是Element提供的,基本都是Element提供的,例外,比如 Node.parentElement
Node只提供了基本的属性和方法。
节点类型概览
12种节点类型,引用www.w3school.com.cn/jsref/prop_…
| 节点类型值 | 节点类型 | 描述 | 子节点 |
|---|---|---|---|
| 1 | Element | 代表元素 | Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference |
| Attr | 代表属性 | Text, EntityReference | |
| 3 | Text | 代表元素或属性中的文本内容。 | None |
| 4 | CDATASection | 代表文档中的 CDATA 部分(不会由解析器解析的文本)。 | None |
| EntityReference | 代表实体引用。 | Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference | |
| Entity | 代表实体。 | Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference | |
| 7 | ProcessingInstruction | 代表处理指令。 | None |
| 8 | Comment | 代表注释。 | None |
| 9 | Document | 代表整个文档(DOM 树的根节点)。 | Element, ProcessingInstruction, Comment, DocumentType |
| 10 | DocumentType | 向为文档定义的实体提供接口 | None |
| 11 | DocumentFragment | 代表轻量级的 Document 对象,能够容纳文档的某个部分 | Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference |
| Notation | 代表 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>
可以看到实际上你以为是纯文本,其实不然。
再看一个熟悉的概念,空白节点。
<div id="parent">
<div class="child"></div>
</div>
<script>
console.log("parent.childNodes", document.getElementById("parent").childNodes);
</script>
div的前后都有白的Text节点。
DOCUMENT_NODE (9)
文档节点, document就是这个玩意的实例。
document.nodeType
// 9
再看看document包含哪些东西:
没错整个我们编写的页面就是document。
小结
今天我们介绍了节点类型,和最常见的三种节点类型。
今天你收获了吗?