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:

    <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>

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:

// 12 tips to learn JavaScript quickly and free.

// 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:


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

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

    do {
      if (, 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.