본문 바로가기
프론트엔드/Javascript

[Javascript] CSS Selector를 통해 엘리먼트 구분하기 Element.matches()

by jinwanseo 2021. 6. 2.
728x90

[자바스크립트 / Javascript] CSS Selector를 통해 엘리먼트 구분하기

Element.matches()

 

 

  기본 형태

//CSS Selector를 통해 엘리먼트 구분하기 
//해당 엘리먼트와 셀렉터가 같다면 true | 다르다면 false 반환
element.matches(CSS Selector); : boolean

 

  샘플 예제

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>matches Example</title>
  <style>
    .apple {
      width :50px;
      height : 50px;
      background : red;
      border-radius : 50%;
      margin-bottom : 10px;
    }
    
    .orange {
      width :50px;
      height : 50px;
      background : orange;
      border-radius : 50%;
      margin-bottom : 10px;
    }
    
    .grape{
      width :50px;
      height : 50px;
      background : purple;
      border-radius : 50%;
      margin-bottom : 10px;
    }
    
    .melon {
      width :50px;
      height : 50px;
      background : green;
      border-radius : 50%;
      margin-bottom : 10px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="apple"></div>
    <div class="orange"></div>
    <div class="grape"></div>
    <div class="melon"></div>
  </div>
  <script>
    document.querySelector('.container').addEventListener('click',e=>{
       if(e.target.matches('.'+e.target.className)){
         console.log(e.target.className);
       }
    });
  </script>
</body>
</html>

 

  결과 출력

728x90

댓글