js实现父选择器
原生JavaScript实现父选择器
原生JavaScript没有直接提供类似jQuery的parent()方法,但可以通过以下方式实现选择父元素的功能:
// 通过parentNode属性获取直接父元素
const parentElement = document.querySelector('.child').parentNode;
// 通过closest方法向上查找匹配选择器的最近父元素
const closestParent = document.querySelector('.child').closest('.parent-selector');
封装通用父选择器函数
可以封装一个更通用的父选择器函数,支持选择特定层级的父元素:

function getParent(element, selector, level = 1) {
let current = element;
while (level-- > 0 && current) {
current = current.parentElement;
if (selector && !current.matches(selector)) {
return null;
}
}
return current;
}
// 使用示例
const child = document.querySelector('.child');
const parent = getParent(child, '.parent-class', 2);
向上查找所有匹配的父元素
如果需要查找所有符合条件的父元素,可以使用以下方法:

function getAllParents(element, selector) {
const parents = [];
let current = element.parentElement;
while (current) {
if (!selector || current.matches(selector)) {
parents.push(current);
}
current = current.parentElement;
}
return parents;
}
事件委托中的父元素查找
在事件处理中经常需要查找父元素:
document.addEventListener('click', function(event) {
const parent = event.target.closest('.parent-class');
if (parent) {
// 处理父元素
}
});
兼容性考虑
Element.closest()方法在现代浏览器中都支持,但在旧版IE中需要polyfill:
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
}
if (!Element.prototype.closest) {
Element.prototype.closest = function(s) {
let el = this;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}






