Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Element.matches()

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

概述

如果当前元素能被指定的css选择器查找到,则返回true,否则返回false.

语法

result = element.mozMatchesSelector(selectorString) 
  • result 的值为 truefalse.
  • selectorString 是个css选择器字符串.

例子

  <div id="foo">This is the element!</div>
  <script type="text/javascript">
    var el = document.getElementById("foo");
    if (el.mozMatchesSelector("div")) {
      alert("Match!");
    }
  </script>

会显示弹出框,因为"div"选择器可以选择到el元素.

异常

SYNTAX_ERR
如果给定的css选择器无效. 在 Gecko 2.0之前,该方法会返回false,2.0之后,会直接抛出异常.

替代方案(Polyfill)

对于不支持 Element.matches() 或Element.matchesSelector(),但支持document.querySelectorAll()方法的浏览器,存在以下替代方案

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;            
        };
}

关于Polyfill的补充:

规范

Specification Status Comment
Selectors API Level 2
Element.matches
Working Draft Initial definition.

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Original support with a non-standard name

(Yes) with the non-standard name webkitMatchesSelector

3.6 (1.9.2) with the non-standard name mozMatchesSelector [1] 9.0 with the non-standard name msMatchesSelector 11.5 with the non-standard nameoMatchesSelector
15.0 with the non-standard name webkitMatchesSelector
5.0 with the non-standard name webkitMatchesSelector
Unprefix version 34 34 (34) ? ? ?
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Original support with a non-standard name ? 1.0 (1.9.2) with the non-standard name mozMatchesSelector [1] ? ? ?
Unprefix version ? 34.0 (34) ? ? ?

 

[1] Prior to Gecko 2.0, invalid selector strings caused false to be returned instead of throwing an exception.()

 

文档标签和贡献者

 此页面的贡献者: nbouvrette, manjun.han, teoli, AlexChao, ziyunfei
 最后编辑者: nbouvrette,