Selecting elements (part 2)

| 1 min read | JavaScript Framework Diet 3/10

In Selecting elements (part 1) we learned how to select elements from the DOM, and how to find elements inside other elements, both with our own $ and $$ helpers.

In part 2, we’re going to review two DOM element instance methods: closest and matches.

Finding the nearest matching parent with closest

Element.closest() traverses the DOM upwards until it finds a parent that matches the specified selector. If nothing was found, it returns null.

While querySelector allows you to find all elements contained in another element, closest allows you to find an element in which another element is contained in.

<ul data-image-gallery>
$$('img').forEach(image => {
  // Log the parent gallery

Read all about Element.closest() on MDN.

Testing selectors on an element with matches

Sometimes you have an element, but want to know whether it matches a certain selector. Here’s where Element.matches() comes in.

matches returns true or false depending on whether the selector applies to the element or not.

<input type="text">
<input type="email">
<input type="checkbox">
$$('input').forEach(input => {
  if (input.matches('[type="checkbox"]')) {
    // Do something...

  // Do something else...

Read all about Element.matches() on MDN.

Element.closest() and Element.matches() will be used a lot more sparingly than $ and $$. They’re lesser known but very powerful when needed.

JavaScript Framework Diet

JavaScript frameworks are great, but overused. Adding small bits of interactivity to an interface shouldn’t mean installing kilobytes of dependencies or introducing complex build tools.

It’s time for a diet. I’m challenging you to build something without a framework, or follow along and learn something along the way.

Series under development, posts are added on a weekly basis.

  1. Introduction
  2. Selecting elements (part 1)
  3. Selecting elements (part 2)
  4. Event delegation
  5. File structure
  6. Dropdowns
  7. Enter and leave transitions
  8. Modals (part 1)
  9. Modals (part 2)
  10. Live updating data


I occasionally send out a newsletter with personal stories, things I’ve been working on in the past month, and interesting things I come across.

Pinky swear that I won't use your data for any other purposes. Your email address will be stored on Mailchimp and nowhere else.

More about JavaScript & Vanilla JS