js 原生方法获取所有兄弟节点
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>js 原生方法获取所有兄弟节点</title>
</head>
<body>
<ul>
<li id="first">1</li>
<li>2</li>
<li>3</li>
</ul>
<script type="text/javascript">
//方法一:
// function sibling(elem) {
// var r = [];
// var n = elem.parentNode.firstChild;
// for(; n; n = n.nextSibling) {
// if(n.nodeType === 1 && n !== elem) {
// r.push(n);
// }
// }
// return r;
// }
//方法二
function sibling(elm) {
var a = [];
var p = elm.parentNode.children;
for(var i = 0, pl = p.length; i < pl; i++) {
if(p[i] !== elm) a.push(p[i]);
}
return a;
}
var siblings = sibling(document.getElementById('first'));
console.log(siblings);
</script>
</body>
</html>
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!