1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/601538/1599749524594-d892b941-d6b6-4438-ade3-3a04780bd6ef.png#align=left&display=inline&height=317&margin=%5Bobject%20Object%5D&name=image.png&originHeight=634&originWidth=955&size=81793&status=done&style=none&width=477.5)

HTMLAnchorelement
HTMLAppletelement
HTMLAreaElement
HTMLAudioElement
HTMLEIement
HTMLBaseElement
HTMLBodyElement
Element:元素型节点,跟标签相对应
SVGAELement
SVGAItGlyphElement
SVGElement
Document:文档根节点
Node
CDATASection:CDATA节点
Text:文本节点
CharacterData字符数据
Comment:注释
Processinglnstruction:处理信息
Documentfragment:文档片段
DocumentType:文档类型

image.png

image.png

  1. Element: <tagname>...</tagname>
  2. Text: text
  3. Comment: <!-- comments -->
  4. DocumentType: <!Doctype html>
  5. ProcessingInstruction: <?a 1?>

Node

DOM 树中的关系属性:

  • parentNode、childNodes、
  • firstChild、lastChild、
  • nextSibling、previousSibling

操作 DOM 树的 API:

  • appendChild、insertBefore
  • removeChild、replaceChild

高级 API:

  • compareDocumentPosition 是一个用于比较两个节点中关系的函数。
  • contains 检查一个节点是否包含另一个节点的函数。
  • isEqualNode 检查两个节点是否完全相同。
  • isSameNode 检查两个节点是否是同一个节点,实际上在 JavaScript 中可以用“===”。
  • cloneNode 复制一个节点,如果传入参数 true,则会连同子元素做深拷贝。

DOM 标准规定了节点必须从文档的 create 方法创建出来,不能够使用原生的 JavaScript 的 new 运算。

  • createElement、createTextNode、createCDATASection、createComment
  • createProcessingInstruction、createDocumentFragment、createDocumentType

    Element 与 Attribute

    Element 表示元素,它是 Node 的子类。Attribute 和 Property 是完全不同的含义,只有特性场景下,两者才会互相关联。可以把元素的 Attribute 当作字符串来看待
    getAttribute、setAttribute、removeAttribute、hasAttribute
    可以把 Attribute 当作节点:getAttributeNode、setAttributeNode
    可以使用 attributes 对象,比如 document.body.attributes.class = “a” 等效于document.body.setAttribute(“class”, “a”)。

    查找元素

    getElementById、getElementsByName、getElementsByTagName、getElementsByClassName,这几个 API 的性能高于 querySelector、querySelectorAll。

    遍历

    DOM API 中还提供了 NodeIterator 和 TreeWalker 来遍历树。提供了过滤功能,还可以把属性节点也包含在遍历之内。

    Range

    Range API 表示一个 HTML 上的范围,这个范围是以文字为最小单位的。
    使用场景: 做底层框架和富文本编辑
    1. var range = new Range(), firstText = p.childNodes[1],
    2. secondText = em.firstChild
    3. range.setStart(firstText, 9) // do not forget the leading space
    4. range.setEnd(secondText, 4)
    5. var fragment = range.extractContents()
    6. range.insertNode(document.createTextNode("aaaa"))