Node 节点
DOM
树结构示例

Node 类型
重要的节点类型是 1、2、3
类型 | nodeType | nodeName | nodeValue | parentNode | childNodes | 示例 |
---|---|---|---|---|---|---|
Element | 1 | 元素标签名 | null | Document 或 Element 对象 | 1,3,8 | <div> 、<p> |
Attribute | 2 | 属性名 | 属性值 | null | 不支持子节点 | href="www.a.com" |
Text | 3 | #text | 节点内文本 | Element 对象 | 不支持子节点 | 我是一段文本 |
Comment | 8 | #comment | 注释内容 | Document 或 Element 对象 | 不支持子节点 | <!-- 注释 --> |
Document | 9 | #document | null | null | 1,3,8,10 | 整个 html 对象 |
DocumentType | 10 | 文档类型名称 | null | Document 对象 | 不支持子节点 | <!DOCTYPE html> |
DocumentFragment | 11 | #document-fragment | null | null | - | 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
:节点类型
parentNode
与 parentElement
区别在 <html>
上,parentNode
返回 #document
,parentElement
返回 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
读写元素内容