当前位置:首页 > JavaScript

js 实现siblings

2026-02-01 05:21:40JavaScript

实现 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);
}

这些实现方式都遵循相同的原理:通过访问元素的父节点,获取所有子节点,然后过滤掉当前元素本身。可以根据具体需求选择适合的版本。

js 实现siblings

标签: jssiblings
分享给朋友:

相关文章

js实现轮播

js实现轮播

实现基础轮播效果 使用HTML结构创建轮播容器和图片元素: <div class="carousel"> <div class="carousel-inner">…

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue…

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…