TIL38 - JS - .matches() Method

Peter D Lee·2020년 9월 29일
0

JavaScript

목록 보기
19/19

.matches()

If you want to select an element, but want to exclude certain elements, or if you want to only select certain elements in the first place, you can use .matches method on a DOM object to return a boolean of whether the object matches the given selector strings argument.

Example

Suppose you have a function, searchBoxUnselected(), that you would like to execute if anywhere on the page is clicked except for on the searchBox input element.

This would be done by adding a 'click' event listener to the body of the HTML, which would include everything on the webpage, but specify an exception so that clicking on the searchBox element would NOT trigger the event handler.

const body = document.querySelector('body');
const searchBox = document.querySelector('.search-box');

function searchBoxUnselected(e) {
  if (!e.target.matches('.search-box') {
    searchBox.style.opacity = 0.3;
  }
}

body.addEventListener('click', searchBoxUnselected);

In the above code, the searchBoxUnselected(e) function will only be run when the element inside the body that is clicked does not match the string selector '.search-box' --> !e.target.matches('.search-box')

0개의 댓글