How to Use the Matches Method in JavaScript?

Estimated read time 2 min read

The matches() method is not a built-in method in JavaScript. It might be present in some JavaScript libraries or frameworks.

In jQuery, for example, the matches() method is used to determine if the specified element matches a selector.

Here’s an example of how to use the matches() method in jQuery:

let element = document.getElementById("myElement");

if ($(element).matches("#myElement")) {
  console.log("Element matches selector");
} else {
  console.log("Element does not match selector");
}

In modern JavaScript, you can use the Element.matches() method, which is supported in most modern browsers, to determine if an element matches a selector.

Here’s an example of how to use the Element.matches() method in modern JavaScript:

let element = document.getElementById("myElement");

if (element.matches("#myElement")) {
  console.log("Element matches selector");
} else {
  console.log("Element does not match selector");
}

If you need to support older browsers, you can use the Element.msMatchesSelector() method for Internet Explorer, or the Element.webkitMatchesSelector() method for WebKit browsers.

Here’s an example of how to use the Element.msMatchesSelector() and Element.webkitMatchesSelector() methods:

let element = document.getElementById("myElement");

if (element.msMatchesSelector("#myElement")) {
  console.log("Element matches selector");
} else if (element.webkitMatchesSelector("#myElement")) {
  console.log("Element matches selector");
} else {
  console.log("Element does not match selector");
}

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply