当前位置:首页 > JavaScript

js closest 实现

2026-04-06 07:39:13JavaScript

实现 closest 方法

closest 是 DOM 元素的一个方法,用于查找与当前元素匹配指定选择器的最近祖先元素(包括自身)。如果未找到匹配的元素,则返回 null

基本用法

const element = document.querySelector('.child');
const closestParent = element.closest('.parent');
console.log(closestParent); // 返回匹配的祖先元素或 null

手动实现 closest

如果需要在旧版浏览器或非标准环境中实现类似功能,可以手动编写 closest 方法:

if (!Element.prototype.closest) {
  Element.prototype.closest = function(selector) {
    let el = this;
    while (el) {
      if (el.matches(selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  };
}

关键点说明

  • matches(selector) 检查当前元素是否匹配选择器。
  • parentElement 用于向上遍历 DOM 树。
  • 如果遍历到 document.documentElement<html>)仍未找到匹配元素,则返回 null

兼容性增强

如果需要支持更旧的浏览器(如 IE9 以下),可以额外实现 matches 方法:

js closest 实现

if (!Element.prototype.matches) {
  Element.prototype.matches = 
    Element.prototype.msMatchesSelector || 
    Element.prototype.webkitMatchesSelector;
}

示例

<div class="grandparent">
  <div class="parent">
    <div class="child"></div>
  </div>
</div>
const child = document.querySelector('.child');
console.log(child.closest('.parent')); // 返回 <div class="parent">
console.log(child.closest('.not-found')); // 返回 null

标签: jsclosest
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现继承

js实现继承

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

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js如何实现继承

js如何实现继承

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

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…