1、父节点
element.parentNode
parentNode属性可返回某节点的父节点,注意是最近的一个父节点
如果没有父节点,返回null
<body>
<div class="grandfather">
<div class="father">
<div class="son">
123
</div>
</div>
</div>
</body>
<script>
var sons = document.querySelector('.son');
//var father = document.querySelector('.father');
//parentNode属性可返回某节点的父节点,注意是最近的一个父节点
//如果没有父节点,返回null
console.log(sons.parentNode);
console.log(sons.parentNode.parentNode);
</script>
2、子节点
element.childNodes (不实用)
element.children(开发常用)
<div class="tab">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li>4</li>
<li>5</li>
<li>6</li>
</ol>
</div>
var tab = document.querySelector('.tab').querySelector('ul');
//childNodes 所有子节点 包括元素节点 文本节点等
console.log(tab.childNodes);
//实际开发使用children获取所有子元素节点
console.log(tab.children);
注:获取第一个字元素或者最后一个子元素
1、element.firstChild / element.lastChild (返回的不只有元素节点,还有文本节点什么的,不推荐使用)
推荐使用:element.firstElementChild / element.lastElementChild (只返回元素节点,只兼容ie9以上)
2、element.children[0] / element.children[element.children.length-1] (实际开发常用,没有兼容性问题)
★兄弟节点
1、获取下一个兄弟节点
element.nextSibling 返回下一个节点,包含文本节点等,没有则返回null
element.previousSibling 返回上一个节点,包含文本节点等,没有则返回null
注意:要想只获得元素节点,使用以下两个,不过有兼容性问题,要求ie9以上
element.nextElementSibling
element.previousELementSibling
可以自己封装一个兼容性的函数
function getNextElementSibling(element){
var el = element;
while(el = el.nextSibling){
if(el.nodeType === 1){
return el;
}
}
return null;
}