原生js获取元素的兄弟节点(previousSibling、nextSibling)、兄弟元素(nextElementSibling、previousElementSibling)
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><div id="box"><div>1</div><div id="s
·
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="box">
<div>1</div>
<div id="second">2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<script>
var sec = document.getElementById('second');
// nextSibling 下一个兄弟节点
console.dir(sec.nextSibling); // #text 换行节点
// previousSibling 上一个兄弟节点
console.dir(sec.previousSibling); // #text 换行节点
// nextElementSibling 下一个兄弟元素
console.dir(sec.nextElementSibling); // div 元素
// previousElementSibling 上一个兄弟元素
console.dir(sec.previousElementSibling); // div 元素
// 解决nextElementSibling的浏览器兼容性问题
function getNextElementSibling(element) {
var el = element;
while (el = el.nextSibling) {
if (el.nodeType === 1) {
return el;
}
}
return null;
}
console.dir(getNextElementSibling(sec)); // div 元素
</script>
</body>
</html>
更多推荐
所有评论(0)