Programming language/javascript
[Dom script] Element.matches() 이벤트 핸들러에서 자주 사용
hello-world
2022. 12. 7. 09:28
728x90
반응형
Element.matches()
프론트엔드를 하다보면 이벤트 클릭을 많이 할 수 밖에 없다.
그럴때 여러 엘리먼트가 중첩되어 있는 경우 타겟을 골라내는 역활을 해주는게 바로 이 Element.matches() 이다.
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
Element 인터페이스의 matches() 메서드는 요소가 지정된 CSS 선택자에 의해 선택되는지 여부를 테스트합니다.
라고 한다.
아래는 예제
HTML
<div>
<button class="click-me">
<span class="text-large">Click Me!</span>
<br>
<span class="text-small">(limited time offer)</span>
</button>
</div>
Javascript
document.addEventListener('click', function (event) {
//.click-me buttons 클릭시에만 if 문 실행
if (event.target.matches('.click-me') ){
console.log('선택요소는 .click-me 선택자 엘리먼트');
};
});
728x90
반응형