通过关系获取节点
作者:互联网
<div id="box1">hello <div class="box2" id="box4">2</div> <div class="box2"> <div class="box3" id="box5"></div> </div> <div class="box2" id="box6">4</div></div>
1.获取父节点
box=document.querySelector("#box4") //获取ID为box4的节点 box.parentElement //获取它的父节点
2.获取子节点
box=document.querySelector("#box1") //获取ID为box1的节点 box.children //获取它的子元素们 box.childNodes //获取它的子节点们
3.获取兄弟节点
box=document.querySelector("#box5") //获取ID为box5的节点 box.nextElementSibling //获取下一个元素 box.nextSibling //获取下一个节点 box.previousElementSibling //获取上一个元素 box.previousSibling //获取上一个节点
4.获取第一个子节点
box = document.querySelector("#box1") //获取ID为box1的节点 box.firstElementChild //获取第一个子节点 box.childNodes[0] //这个也可以获取第一个子节点
5.获取第一个子元素
box = document.querySelector("#box1") //获取ID为box1的节点 box.firstChild //获取第一个子元素 box.children[0] //这个也可以获取第一个子元素
6.获取最后一个子元素
box = document.querySelector("#box1") //获取ID为box1的节点 box.lastChild //获取最后一个元素 box.children[box.children.length-1] //这个也可以获取最后一个子元素
7.获取最后一个子节点
box = document.querySelector("#box1") //获取ID为box1的节点 box.lastChild //获取最后一个子节点 box.childNodes[box.childNodes.length-1] //这个也可以获取最后一个子节点
8.获取这个元素是在同胞中的下标为多少
Object.prototype.IndexOf=function(){ var arr=this.parentElement.children for(let i=0;i<arr.length;i++){ if(arr[i]===this){ return i } } }
注意:元素与节点不同,元素是指标签,而节点不只包括标签,也包括文本.回车等。
标签:关系,box,获取,querySelector,document,box1,节点 来源: https://www.cnblogs.com/forever-ljf/p/16478925.html