700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > WebAPI-DOM树 获取父节点 获取子节点的方法汇总

WebAPI-DOM树 获取父节点 获取子节点的方法汇总

时间:2021-07-27 19:29:31

相关推荐

WebAPI-DOM树 获取父节点 获取子节点的方法汇总

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。