有没有办法测试选择器是否匹配给定的DOM元素?优选地,不使用像Sizzle这样的外部库.这是一个库,我想尽量减少"核心"库所需的第三方插件的数量.如果它最终需要Sizzle我只是将它作为插件添加到库中,以便那些想要它将启用的功能.
例如,我可以做类似的事情:
var element = <input name="el" />
matches("input[name=el]", element) == true
Run Code Online (Sandbox Code Playgroud)
编辑:在考虑了更多之后,我提出了一个解决方案,这在技术上有效,但在效率方面似乎不是最佳的:
function matchesSelector(selector, element) {
var nodeList = document.querySelectorAll(selector);
for ( var e in nodeList ) {
return nodeList[e] === element;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
基本上,函数使用给定的选择器查询整个文档,然后迭代nodeList.如果给定元素在nodeList中,则返回true,如果不是,则返回false.
如果有人能够提出更有效的答案,我很乐意将他们的答案标记为答案.
编辑:Flavius Stef向我指出了Firefox 3.6+,mozMatchesSelector的浏览器特定解决方案.我还发现Chrome的等价物(版本兼容性未知,它可能在Safari或其他webkit浏览器上有效或不起作用):, webkitMatchesSelector这与Firefox实现基本相同.我还没有找到IE浏览器的任何原生实现.
对于上面的示例,用法将是:
element.(moz|webkit)MatchesSelector("input[name=el]")
Run Code Online (Sandbox Code Playgroud)
似乎W3C也在Selectors API Level 2(此时仍为草案)规范中解决了这个问题.matchesSelector一旦批准,将成为DOM元素的方法.
W3C用法: element.matchesSelector(selector)
Since that specification is still a draft and there is a lag time before popular browsers implement the methods …