matches

Previous methods were searching the DOM.
The elem.matches(css) does not look for anything, it merely checks if elem matches the given CSS-selector. It returns true or false.
The method comes in handy when we are iterating over elements (like in an array or something) and trying to filter out those that interest us.

For instance:

  1. <a href="http://example.com/file.zip">...</a>
  2. <a href="http://ya.ru">...</a>
  3. <script>
  4. // can be any collection instead of document.body.children
  5. for (let elem of document.body.children) {
  6. if (elem.matches('a[href$="zip"]')) {
  7. alert("The archive reference: " + elem.href );
  8. }
  9. }
  10. </script>

closest

Ancestors of an element are: parent, the parent of parent, its parent and so on. The ancestors together form the chain of parents from the element to the top.
The method elem.closest(css) looks the nearest ancestor that matches the CSS-selector. The elem itself is also included in the search.
In other words, the method closest goes up from the element and checks each of parents. If it matches the selector, then the search stops, and the ancestor is returned.
For instance:

  1. <h1>Contents</h1>
  2. <div class="contents">
  3. <ul class="book">
  4. <li class="chapter">Chapter 1</li>
  5. <li class="chapter">Chapter 1</li>
  6. </ul>
  7. </div>
  8. <script>
  9. let chapter = document.querySelector('.chapter'); // LI
  10. alert(chapter.closest('.book')); // UL
  11. alert(chapter.closest('.contents')); // DIV
  12. alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
  13. </script>

image.png