I'm working on an application that only has jQuery 1.1 installed which dosn't support the .closest method.
My script currently looks like this:
$('.navPanel').find('img').closest('td').hide();
So I'm looking for every image in the .navPanel and traversing up the DOM and hiding the td that it sits in. Does anyone know if there is a vanilla JavaScript function I could simply add to my script that polyfills the missing .closest method?
Thanks for your time.
jQuery and its cousins are great, and by all means use them if it makes it easier to develop your application. If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency.
"VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery back in the days. People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries." Or, in our case, without new, fancy frameworks.
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.
Modern browsers have the Element.closest() method.
Example:
document.querySelector('.navPanel img').closest('td')
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
Here you can check which browsers have built-in support: https://caniuse.com/#feat=element-closest
When there is no support in the browser the following polyfill could be used: https://github.com/jonathantneal/closest
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