js 实现sublings
实现 siblings 的方法
在 JavaScript 中,siblings 是指当前元素的所有兄弟元素(即共享同一个父元素的元素)。以下是几种实现方式:
使用纯 JavaScript 实现
通过 parentNode 和 children 属性遍历兄弟元素:

function getSiblings(element) {
const siblings = [];
let sibling = element.parentNode.firstChild;
while (sibling) {
if (sibling.nodeType === 1 && sibling !== element) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
}
使用 ES6 和 Array.filter
利用 Array.from 和 filter 方法简化代码:

function getSiblings(element) {
return Array.from(element.parentNode.children)
.filter(child => child !== element);
}
使用 jQuery 实现
如果项目中已引入 jQuery,可以直接使用 siblings() 方法:
const siblings = $(element).siblings();
扩展原生 Element 原型
为所有 DOM 元素添加 siblings 方法:
Element.prototype.siblings = function() {
return Array.from(this.parentNode.children)
.filter(child => child !== this);
};
// 使用方式
const siblings = element.siblings();
注意事项
- 纯 JavaScript 方法需要考虑节点类型(
nodeType === 1表示元素节点)。 - jQuery 方法简洁但需要引入库。
- 扩展原型可能影响全局环境,需谨慎使用。






