Get closest parent element (excluding current element) using a selector

Viewed 6862

I am trying to get the closest Parent element of an element.

Looking at .closest(), it seems to return the element itself if the selector matches with it:

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

(emphasis is mine)

So, what would be the best way to get the closest Parent of an element given a selector?

Example

var el = document.getElementById('foo');
var closestParent = el.closest('div');
console.log(closestParent);
<div>root
  <div>level1
    <div id='foo'>level2</div>
  </div>
</div>

As you can see, el.closest('div'); returns el itself, not its closest parent matching the selector div (level1), which is what I need.

I know that in this case I can simply do closestParent.parentElement, but this is just an example, and I am trying to figure out if it possible to avoid .closest() to return the element itself.

2 Answers

The closest function is returning the correct element. It is looking for the nearest div, which happens to be itself.

If you had a structure like this:

<div>root
  <div>level1
    <span id='foo'>level2</span>
  </div>
</div>

Then you would get the level1 parent with your code.

If you want to exclude the current element, just use parentNode

var el = document.getElementById('foo');
var closestParent = el.parentNode.closest('div');
console.log(closestParent);

Document of Closest Here is a DOM, it isn't about parent it's about the nearest Element so you can change your query like below but if you need parents just use parentEelement

var el = document.getElementById('foo');
var closestParent = el.closest('div:not(#foo)');
console.log(closestParent);
<div>root
  <div>level1
    <div id='foo'>level2</div>
  </div>
</div>

Related