Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM / pure JavaScript solution to jQuery.closest() implementation?

Tags:

People also ask

Can I use pure JS with jQuery?

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.

How do you use the closest function in JavaScript?

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.

How does closest work in jQuery?

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.

What is Event target closest?

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