How to get the closest element by selector using JavaScript

published: 27 Aug 2022

2 min read

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>How to learn JavaScript</h2>
    <div>
        <p>12 tips to learn JavaScript quickly and free.</p>
        <time>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;
  };
}

How to get the closest element by selector using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming