본문 바로가기
Language/JavaScript

[JavaScript] element.matches() - 해당 엘리먼트가 CSS 선택자(selector)로 선택이 되는지 여부 확인

by 썸머워즈 2022. 5. 27.
반응형

matches() 메서드는 기준 element가 CSS 선택자처럼 (예를 들어 #id, .class, [href ^= https] 등의 선택자들) 선택이 되는지 여부를 확인하는 메서드다. 

 

▷ 구문

targetElement.matches(selectorString);

selectorString: CSS 선택자와 동일한 표현식의 문자열


▷ 예제 1) matches 사용법

<!DOCTYPE html>
<html lang="ko">
  <head>
    <script src="./test.js" defer></script>
    <title>mineItRecord</title>
  </head>
  <body>
    <div id="div-0">Here is id div-01</div>
    <div id="div-1">Here is id div-02</div>
    <div class="div-2">Here is class div-03</div>
    <a href="https://mine-it-record.tistory.com/" class="anc">mineItRecord</a>
  </body>
</html>
const div0 = document.querySelector('#div-0');
const div1 = document.querySelector('#div-1');
const div2 = document.querySelector('.div-2');
const anc = document.querySelector('.anc');

div0.matches('#div-0'); // true
div1.matches('#div-1'); // true
div2.matches('#div-2'); // false
div2.matches('.div-2'); // true
anc.matches('[href="https"]'); // false
anc.matches('[href^="https"]'); // true
anc.matches('[href*="mine-it-record"]'); // true

 

예제에서 사용된 것 처럼 다양한 css selector를 사용하고, 그 선택자로 선택이 되는지를 확인시켜주는 메서드이다.

당연히 선택자로 사용될 수 없는 문자열이 들어가면 에러를 출력하니 잘 사용해야 한다.

 

이런 식으로 matches를 사용하게 되면 굳이 element.classList.contains('div-2') 같은 방식을 안 써도 더 짧게 체크가 가능하다.


참고: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

 

Element.matches() - Web APIs | MDN

The matches() method of the Element interface tests whether the element would be selected by the specified CSS selector.

developer.mozilla.org

반응형


댓글

TOP