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.
parentNode gives the parent, while . parentElement gives undefined.
The closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.
The closest() method in JavaScript is used to retrieve the closest ancestor, or parent of the element matches the selectors. If there is no ancestor found, the method returns null.
closest() The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With