js closest 实现
实现 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 方法:

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






