Get the closest element by selector using JavaScript

To get the closest element by a selector, you can use the element's closest() method. This method starts with the target Element and traverses up through its ancestors in the DOM tree until it finds the element that matches the selector.

The closest() method returns the first element that matches the selector. If no such element exists, it returns null.

Let us say you have the following HTML code snippet:

<article>
    <h2 class="title">How to learn JavaScript</h2>
    <div class="meta">
        <p class="subtitle">12 tips to learn JavaScript quickly and free.</p>
        <time class="published">August 21, 2019</time>
    </div>
</article>

The following example selects the closest <div> element of the selected element:

const elem = document.querySelector('time');

// select closest <div>
const div = elem.closest('div');

console.log(div.classList[0]); // meta

Here is an another example that selects the closest <article> element in the DOM tree:

const elem = document.querySelector('time');

const article = elem.closest('article');

console.log(article.tagName); // article

The closest() method doesn't work for siblings. For example, you can not select the <p> tag because it is a sibling of <time> and not its parent. The same logic applies to <h2> tag because it is not a parent node of <time> in the DOM tree:

elem.closest('p'); // null
elem.closest('h2'); // null

To select a sibling of an element, you have to first select the closest parent element and then use querySelector() to find the sibling within:

elem.closest('div').querySelector('p').innerText; 
// 12 tips to learn JavaScript quickly and free.

elem.closest('article').querySelector('h2').innerText; 
// How to learn JavaScript

The closest() method only works in modern browsers and doesn't support Internet Explorer. To support IE9 and above, you can use the following polyfill:

// https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill

if (!Element.prototype.matches) {
  Element.prototype.matches =
    Element.prototype.msMatchesSelector || 
    Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
  Element.prototype.closest = function(s) {
    var el = this;

    do {
      if (Element.prototype.matches.call(el, s)) return el;
      el = el.parentElement || el.parentNode;
    } while (el !== null && el.nodeType === 1);
    return null;
  };
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.