DOM树
DOM树 又称为 文档树模型,就是把文档映射成树形结构,通过节点对象对其处理,处理的结果可以加载到当前的页面中。
DOM树 就像人类家族的族谱,族谱可以很容易的表明家族成员之间的关系,将复杂的关系简明地表示出来。
节点操作
获取父节点
通过parentNode
属性可以获取指定节点的父节点;如果指定的节点没有父节点就会返回 null,如果存在则返回父节点对象
语法:
node.parentNode
node
需要获取父节点的节点<button id="btn">按钮</button><div id="box"><span id="sp">span元素</span></div><script>function $(id) {return document.getElementById(id)}$('btn').onclick = function() {// 获取元素父节点并打印console.log($('sp').parentNode)}</script>
获取子节点
childNodes
parentNodes
该属性用于获取指定节点的所有子节点(包含元素节点、文本节点、注释节点);返回值为节点集合,集合中的元素为节点对象;如果没有子节点则返回值为空集合
语法:
element.childNodes
element
需要获取子节点的元素对象示例:
<button id="btn">按钮</button><div id="box"><!-- 注释内容 --><span id="sp">span元素</span></div><script>function $(id) {return document.getElementById(id)}$('btn').onclick = function() {// 获取所有子节点,并打印console.log($('box').childNodes)}</script>
children
children
属性用于获取指定元素的所有子元素;返回值为元素集合
与 childNodes 不同 childNodes 属性返回所有的节点(包含本节点、注释节点);children
属性只返回元素节点
需要注意的是children
属性是一个非标准属性,但多数浏览器都支持,所以可以放心使用
<button id="btn">按钮</button><div id="box"><!-- 注释内容 --><span id="sp">span元素</span></div><script>function $(id) {return document.getElementById(id)}$('btn').onclick = function() {// 获取所有子元素节点,并打印console.log($('box').children)}</script>
firstChild
firstChild
获取指定节点的第一个子节点;若没有子节点则返回 null
语法:
node.firstChild
<button id="btn">按钮</button><div id="box"><!-- 注释内容 --><span id="sp">span元素</span></div><script>function $(id) {return document.getElementById(id)}$('btn').onclick = function() {// 获取指定元素的第一个子节点(文本节点),并打印console.log($('box').firstChild)}</script>
lastChild
lastChild
获取指定节点的最后一个子节点;若没有子节点则返回 null
语法:
node.lastChild
firstElementChild
firstElementChild
返回指定节点中的第一个子元素节点;没有子元素则返回 null
语法:
node.firstElementChild
示例:
<button id="btn">按钮</button><div id="box"><!-- 注释内容 --><span id="sp">span元素</span><p>p元素</p></div><script>function $(id) {return document.getElementById(id)}$('btn').onclick = function() {// 获取指定元素的第一个子元素节点,并打印console.log($('box').firstElementChild)}</script>
lastElementChild
lastElementChild
返回指定节点中的最后一个子元素节点;没有子元素则返回 null