How To Use Matches() In JavaScript: Simplest Explanation

How To Use Matches() In JavaScript: Simplest Explanation

·

2 min read

In this post, I will explain how matches() works in JavaScript in the simplest possible way.

Matches() is a function that every HTML element comes with built-in.

Its basic syntax is:

TheElement.matches(some CSS selector);

Matches() will check if the element has some CSS selector(s). The CSS selectors can be an id, a class, a p/div/span tag...etc.

If our element matches the selector, matches will return true. Otherwise, it will return false.

Example

<html>
<head><title></title></head>
<script>
window.onload = function()
{
let thing = document.getElementById("thing");
thing.matches("#thing");
thing.matches(".red");
thing.matches("div.red");
}
</script>
<body>
<p id="thing" class="blue">  


</p>
</body>
</html>

Results Screen Shot 2022-07-23 at 6.08.58 PM.png

In the above example, our first console.log() will return true. The second console.log() will return true. The third console.log will also return false (even though it is a divider tag, it does not have a class of red).

Where is Matches() Used In The Real World?

One common way to use matches() is with event delegation. Event delegation is where we give an event listener to some children of a parent. I have another more detailed article on event delegation, but to show you a simple example

Example

<div id="buttons">  
  <button class="buttonClass">Click me</button>
  <button class="buttonClass">Click me</button>
  <!-- buttons... 
  <button class="buttonClass">Click me</button>
</div>
<script>
  document.getElementById('buttons')
    .addEventListener('click', event => {  
      if (event.target.className === 'buttonClass') { 
        console.log('Click!');
      }
    });
</script>

In event delegation, we set an event listener for the parent and then (since the event will apply to children by default) we check if the child matches a particular criterion.

And if so, the event is triggered, and we execute the assigned function, otherwise we don't do anything.

So that is more or less how matches() works.