js实现closest
实现 closest 方法
closest 方法用于查找与当前元素匹配的选择器的最近祖先元素。以下是一个纯 JavaScript 的实现方式:
function closest(element, selector) {
if (!element || !selector) return null;
while (element) {
if (element.matches(selector)) {
return element;
}
element = element.parentElement;
}
return null;
}
使用示例
const childElement = document.querySelector('.child');
const parentElement = closest(childElement, '.parent');
console.log(parentElement);
兼容性处理
如果需要支持旧版浏览器,可以添加 matches 方法的 polyfill:

if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
const matches = (this.document || this.ownerDocument).querySelectorAll(s);
let i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
注意事项
- 该方法会从当前元素开始向上查找,直到找到匹配的元素或到达文档根节点。
- 如果未找到匹配元素,返回
null。 - 确保传入有效的 DOM 元素和选择器字符串。






