js closest 实现
实现 closest 方法
closest 方法用于查找与当前元素匹配指定选择器的最近祖先元素。如果不存在匹配的祖先元素,则返回 null。以下是手动实现 closest 的方法:

function closest(element, selector) {
while (element) {
if (element.matches(selector)) {
return element;
}
element = element.parentElement;
}
return null;
}
使用示例
假设有以下 HTML 结构:

<div class="ancestor">
<div class="parent">
<div class="child"></div>
</div>
</div>
查找 .child 元素的最近 .ancestor 祖先:
const child = document.querySelector('.child');
const ancestor = closest(child, '.ancestor');
console.log(ancestor); // 输出: <div class="ancestor">...</div>
兼容性处理
如果需要支持旧版浏览器,可以添加 matches 方法的兼容性处理:
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.webkitMatchesSelector ||
Element.prototype.msMatchesSelector;
}
注意事项
matches方法用于检查元素是否匹配指定的选择器。parentElement属性用于获取元素的父元素。- 循环会一直向上查找,直到找到匹配的元素或到达文档根元素。






