我正在寻找一种有效的方法来检查 DOM 节点的任何父节点是否具有给定的 CSS 类。
我的问题与这个非常相似: Check if class exists somewhere in parent - vanilla JS ,除了我明确寻求有关如何以最有效的方式实现这一点的建议(此代码将被经常调用)。
上述问题的公认答案建议采用递归解决方案。我想知道是否有更有效的方法。
最佳答案
如果您喜欢漂亮的语法,请使用 matchesSelector
方法(caniuse)。
此方法已经进行了一些名称更改,并且仍然带有前缀,因此要使用它,请规范化名称:
var matchesSelector;
['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
var name = prefix + 'atches';
if (name in document.documentElement) {
matchesSelector = name;
}
name += 'Selector';
if (name in document.documentElement) {
matchesSelector = name;
}
return matchesSelector; // If found, then truthy, and [].some() ends.
});
确定名称后,可以按如下方式使用:
// Usage
element[matchesSelector]('.someclass *');
或者只是扩展原型(prototype):
Element.prototype.matches = Element.prototype[matchesSelector];
// Usage
element.matches('.someclass *');
关于javascript - 有效检查 DOM 节点的任何父节点中的 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333530/