Vanilla JavaScript.closest without jQuery

I am working on an application that only has jQuery 1.1 installed, which does not support the .closest method.

Now my script looks like this:

$('.navPanel').find('img').closest('td').hide(); 

So, I look for every image in .navPanel and examine the DOM and hide the td it sits in. Does anyone know if there is a vanilla JavaScript function that I could just add to my script that polyfills the missing .closest method?

Thank you for your time.

+14
source share
4 answers

You can use .parents() with the eq selector. both parents and the equalizer selector are added in version 1.0:

 $('.navPanel').find('img').parents('td').eq(0).hide(); 
-ten
source

Modern browsers have an Element.closest () method.

Example:

 document.querySelector('.navPanel img').closest('td') 

Link: 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

If the browser does not have support, you can use the following polyfill: https://github.com/jonathantneal/closest

+41
source
 myImage.parentNode; 

Like vanilla, how is it obtained. Remove this in a loop until you click the desired tag type:

 while(thisTag.parentNode.tagName !== 'TD') // uppercase in HTML, lower in XML { thisTag=thisTag.parentNode; } 

This should do the trick in plain old js.

Danny

+27
source

Because IE still does not support element.closest() the easiest thing to do is to use polyfill.

Include the following js this is a polyfill for closest ()

 (function (ElementProto) { if (typeof ElementProto.matches !== 'function') { ElementProto.matches = ElementProto.msMatchesSelector || ElementProto.mozMatchesSelector || ElementProto.webkitMatchesSelector || function matches(selector) { var element = this; var elements = (element.document || element.ownerDocument).querySelectorAll(selector); var index = 0; while (elements[index] && elements[index] !== element) { ++index; } return Boolean(elements[index]); }; } if (typeof ElementProto.closest !== 'function') { ElementProto.closest = function closest(selector) { var element = this; while (element && element.nodeType === 1) { if (element.matches(selector)) { return element; } element = element.parentNode; } return null; }; } })(window.Element.prototype); 

and then this is exactly the same as IE would understand it, and everything works without any other changes.

from Jonathantneal / nearest

+5
source

Source: https://habr.com/ru/post/982198/


All Articles