Marat Tanalin的解决方案很好,但标准语法elem.matchesSelector
是elem.matches
:
function getAncestorBySelector(elem, selector) {
if (!elem.matches(selector + ' ' + elem.tagName)) {
// If element is not inside needed element, returning immediately.
return null;
}
// Loop for finding an ancestor element that matches your selector.
}
不幸的是,并非所有浏览器都支持这种语法。一些浏览器仍然实现了前缀版本,elem.matchesSelector
而 Opera Mini 根本不支持此功能。
为了缓解这个问题,您可以按照 MDN的建议将描述的方法与以下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) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
或者,您可能要考虑完全抛弃elem.matchesSelector
并使用以下内容:
function getAncestorBySelector(elem, selector) {
if([].indexOf.call(document.querySelectorAll(selector + ' ' + elem.tagName), elem) === -1) {
// If element is not inside needed element, returning immediately.
return null;
}
// Loop for finding an ancestor element that matches your selector.
}
两种实现都至少需要支持querySelectorAll
,这是所有现代浏览器都支持的功能。
浏览器支持: