jQuery isn't a separate programming language. It's a JavaScript library. Whether you use jQuery or not, it's still "pure JavaScript". JavaScript is designed for both functional and object-oriented programming.
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 returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
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.
Here's the markup i'm trying to query. So given the markup:
<table class="non-unique-identifier table">
<tr><td><div id="unique-identifier"></div></td></tr>
</table>
I'm querying for #unique-identifier:
var myDiv = document.getElementById('#unique-identifier');
I'm then trying to select the table. The issue is that i want to make the code not brittle so i don't need to do this:
var myDiv = document.getElementById('#unique-identifier'),
myTable = myDiv.parentNode.parentNode.parentNode.parentNode;
My question
Is there currently a DOM implementation of the jQuery equivalent of $().closest() ? A closest implementation that is efficient without nested for loops would be preferred.
Limitations
I'm required to not use jQuery or sizzle for this particular issue or introduce any new libraries. The code is quite old as well. Thus, that is the reason for such limitations and the existence of <tables>
.
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