Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla JavaScript .closest without jQuery

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.

like image 216
William Li Avatar asked Feb 09 '15 09:02

William Li


People also ask

Do you need to use jQuery?

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.

Is vanilla JavaScript same as JavaScript?

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

What is .closest in JavaScript?

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.


1 Answers

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

like image 114
jpoppe Avatar answered Oct 01 '22 07:10

jpoppe