mozilla
Your Search Results

    Element.matches()

    Summary

    The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

    Several browsers implement this, prefixed, under the non-standard name matchesSelector().

    Syntax

    result = element.matches(selectorString) 
    
    • result holds the return value true or false.
    • selectorString is a string representing the selector to test.

    Example

    <div>This is some element</div>
    <div class="someClass">This is THE element!</div>
    <script type="text/javascript">
      var coll = document.getElementsByTagName("div");
      for (var i = 0, len = coll.length; i < len; i++) {
        if (coll[i].matches(".someClass")) {
          alert("Match!");
        }
      }
    </script>
    

    This will alert, since the element has indeed a class attribute with value someClass.

    Exceptions

    SYNTAX_ERR
    The specified selector string is invalid.

    Polyfill

    For browsers that do not support Element.matches() or Element.matchesSelector(), but carry support for document.querySelectorAll(), a polyfill exists:

    ​function (selector) {
      var element = this;
      var matches = (element.document || element.ownerDocument).querySelectorAll(selector);
      var i = 0;
      
      while (matches[i] && matches[i] !== element) {
        i++;
      }
    
      return matches[i] ? true : false;
    }

    Specification

    Specification Status
    DOM
    The definition of 'Element.prototype.matches' in that specification.
    Living Standard

    Browser compatibility

    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 name oMatchesSelector
    15.0 with the non-standard name webkitMatchesSelector
    5.0 with the non-standard name webkitMatchesSelector
    Unprefix version 34 34 (34) ? ? 7.1
    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) ? ? 8

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

    Document Tags and Contributors

    Last updated by: fscholz,
    Hide Sidebar