6 August 2024

Instead of querySelector you should use matches(). The matches() method in JavaScript is used to determine if an element would be selected by a specified CSS selector. This method returns true if the element matches the selector, and false otherwise.

Source code viewer
  1. /* <div id="myDiv" class="container highlight">Hello, World!</div> */
  2. const element = document.getElementById('myDiv');
  3.  
  4. console.log(element.matches('.container')); // true
  5. console.log(element.matches('.highlight')); // true
  6. console.log(element.matches('#myDiv')); // true
  7. console.log(element.matches('.nonexistent-class')); // false
Programming Language: ECMAScript