How to Check If the Specified Selector Matches an Element in JavaScript

08/02/2021

Contents

In this article, you will learn how to check if the specified selector matches an element in JavaScript.

Checking if the specified selector matches an element in JavaScript

In JavaScript, you can check if a specified selector matches an element using the matches() method. This method returns a boolean value that indicates whether the element matches the specified selector or not.

Example
const element = document.querySelector('.my-class');
const matchesSelector = element.matches('.my-class');
console.log(matchesSelector); // Output: true

This example first gets the element using the querySelector() method, and then checks if it matches the specified selector using the matches() method. The matchesSelector variable will be set to true if the element matches the selector, and false otherwise.

You can also use the matches() method with a variable that contains the selector.

Example
const element = document.querySelector('.my-class');
const selector = '.my-class';
const matchesSelector = element.matches(selector);
console.log(matchesSelector); // Output: true

This example first gets the element using the querySelector() method, and then creates a variable selector that contains the selector. The matches() method is then called with the selector variable to check if the element matches the selector.

It’s worth noting that the matches() method is not supported in older browsers, such as Internet Explorer. In those cases, you can use the msMatchesSelector method or the webkitMatchesSelector method, depending on the browser.

Example
const element = document.querySelector('.my-class');
const matchesSelector = element.matches('.my-class') ||
                        element.msMatchesSelector('.my-class') ||
                        element.webkitMatchesSelector('.my-class');
console.log(matchesSelector); // Output: true

This example first gets the element using the querySelector() method, and then checks if it matches the specified selector using the matches() method. If the matches() method is not supported, the msMatchesSelector method or the webkitMatchesSelector method is used instead.