js 实现siblings
实现 siblings 方法
在 JavaScript 中,可以通过遍历 DOM 元素的父节点子元素列表来获取所有兄弟节点(siblings)。以下是几种实现方式:
使用纯 JavaScript 实现
function siblings(element) {
if (!element.parentNode) return [];
const children = Array.from(element.parentNode.children);
return children.filter(child => child !== element);
}
// 示例用法
const el = document.querySelector('.target');
const siblingsList = siblings(el);
扩展 Element.prototype
Element.prototype.siblings = function() {
if (!this.parentNode) return [];
const children = Array.from(this.parentNode.children);
return children.filter(child => child !== this);
};
// 示例用法
const el = document.querySelector('.target');
const siblingsList = el.siblings();
包含当前元素的版本
如果需要包含当前元素在内的所有兄弟节点:
function siblings(element, includeSelf = false) {
if (!element.parentNode) return [];
const children = Array.from(element.parentNode.children);
return includeSelf ? children : children.filter(child => child !== element);
}
使用 jQuery 风格实现
function $(selector) {
const el = document.querySelector(selector);
return {
siblings: function() {
if (!el.parentNode) return [];
const children = Array.from(el.parentNode.children);
return children.filter(child => child !== el);
}
};
}
// 示例用法
const siblingsList = $('.target').siblings();
考虑文本节点的情况
如果需要包含文本节点在内的所有兄弟节点:
function siblings(element, includeTextNodes = false) {
if (!element.parentNode) return [];
const children = includeTextNodes
? Array.from(element.parentNode.childNodes)
: Array.from(element.parentNode.children);
return children.filter(child => child !== element);
}
这些实现方式都遵循相同的原理:通过访问元素的父节点,获取所有子节点,然后过滤掉当前元素本身。可以根据具体需求选择适合的版本。







