Join MDN and developers like you at Mozilla's View Source conference, 12-14 September in Berlin, Germany. Learn more at https://viewsourceconf.org

Element.mozMatchesSelector

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.

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 id="foo">This is the element!</div>
  <script type="text/javascript">
    var el = document.getElementById("foo");
    if (el.matches("div")) {
      alert("Match!");
    }
  </script>

This will alert, since the element is indeed a <div>.

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 Comment
Selectors API Level 2
The definition of 'Element.matches' in that specification.
Working Draft Initial definition.

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: teoli,