<div id ="father">
<div id='target'>
<div id="children1"></div>
<div id="children2"></div>
<div id="children3"></div>
</div>
</div>
1. js获取元素子节点
父节点ID为target,有两个字节点,获取target下所有字节点
const childrens = document.getElementById('target').getElementTagName('div');
得出的childrens是一个数组,数组中的元素是target下的子节点。
childNodes返回的是子节点的集合,是一个数组形式。
const childrens = document.getElementById('target').childNodes;
同样会返回一个以子节点为元素的数组
const childrens = document.getElementById('target').children;
const children = document.getElementById('target').firstElementChild;
const children = document.getElementById('target').lastChild;
const children = document.getElementById('target').lastElementChild;
2. js获取元素父节点
获取目标元素的直接父元素
const father = document.getElementById('target').parentNode;
获取目标元素的直接父元素
,和parentNode一样。但是parentElement是IE标准
const father = document.getElementById('target').parentElement;
获取目标元素的所有父节点,直接能够获取到所有父亲节点, 这个对应的值是body下的所有节点信息
const fathers = document.getElementById('target').offsetParent;
3. js获取元素兄弟节点
const brother1 = document.getElementById('children1').parentNode.children[1];
previousSibling会匹配字符,包括换行和空格,而不是节点。previousElementSibling则直接匹配节点。
const brother1 = document.getElementById("children2").previousElementSibling;
const brother2 = document.getElementById("children2").previousSibling;
同previousSibling和previousElementSibling,nextSibling和nextElementSibling也是类似的。
const brother1 = document.getElementById("children2").nextElementSibling;
var brother2 = document.getElementById("children2").nextSibling;