Skip to content
本页目录

Node 节点

DOM 树结构示例

Node 类型

重要的节点类型是 1、2、3

类型nodeTypenodeNamenodeValueparentNodechildNodes示例
Element1元素标签名nullDocumentElement 对象1,3,8<div><p>
Attribute2属性名属性值null不支持子节点href="www.a.com"
Text3#text节点内文本Element 对象不支持子节点我是一段文本
Comment8#comment注释内容DocumentElement 对象不支持子节点<!-- 注释 -->
Document9#documentnullnull1,3,8,10整个 html 对象
DocumentType10文档类型名称nullDocument 对象不支持子节点<!DOCTYPE html>
DocumentFragment11#document-fragmentnullnull-DocumentFragment 节点

元素获取与属性操作

获取元素

  • document.querySelect()
  • document.querySelectAll() 获取到的是类数组节点对象列表
  • document.getElementsByClassName()
  • document.getElementsByTagName()
  • document.getElementsByName()
  • document.getElementById()

以上两类获取元素的方式结果又差异,query 获取的是 Node 节点,get 获取的是 HTMLCollection

获取属性

  • node.getAttribute(attrName):返回节点某个属性的值
  • node.getAttributeNames():返回节点所有属性值的数组
  • node.getAttributeNode(attrName):返回属性与值,其 .value 对应属性的值
  • node.hasAttribute(attrName):返回是否存在该属性,布尔值
  • node.hasAttributes():返回当前节点是否存在属性,布尔值
  • node.toggleAttribute(attrName):切换节点的某个属性的值
  • node.removeAttribute(attrName):移除节点的某个属性的值

创建节点

  • createDocumentFragment():创建一个DOM片段
  • createElement():创建一个具体的元素
  • createTextNode():创建一个文本节点

属性

  • node.childNodes:返回包含指定节点的子节点即时更新的集合
  • node.firstChild:返回 childNodes 中第一个节点,没有则返回 null
  • node.lastChild: 返回 childNodes 中最后一个节点,没有则返回 null
  • node.nextSibling:返回当前节点的后一个兄弟节点,没有则返回 null
  • node.parentNode:返回指定的节点在 DOM 树中的父节点
  • node.parentElement:返回指定的节点在 DOM 树中的父节点,不存在返回 null
  • node.previousSibling:返回当前节点的前一个兄弟节点,没有则返回 null
  • node.textContent:读取或写入当前节点及其后代节点的文本内容
  • node.nodeName:节点名称
  • node.nodeValue:读取或写入当前节点内容
  • node.nodeType:节点类型

parentNodeparentElement 区别在 <html> 上,parentNode 返回 #documentparentElement 返回 null

实例方法

Node 操作

  • node.insertBefore(newNode, referenceNode):在参考节点之前插入一个拥有指定父节点的子节点
  • node.appendChild(childNode):将一个节点附加到指定父节点的子节点列表的末尾处
  • node.cloneNode(bool):返回调用该方法的节点的一个副本,true 为克隆元素及其后代,false 只克隆本身
  • node.replaceChild(newChild, oldChild):用指定的节点替换当前节点的一个子节点,并返回被替换掉的节点
  • node.removeChild(childNode):从 DOM 中删除一个子节点并返回删除的节点

获取与比较

  • node.getRootNode():获取根节点,即 #document
  • node.contains(otherNode)node 是否包含 otherNode
  • node.hasChildNodes():当前节点是否有子节点
  • node.isEqualNode(otherNode):两个节点是否相等

innerHTML 与 innerText

  • innerHTML 读写元素
  • innerText 读写元素内容