没有jQuery的Vanilla JavaScript .closest [英] Vanilla JavaScript .closest without jQuery

查看:80
本文介绍了没有jQuery的Vanilla JavaScript .closest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个只安装了jQuery 1.1且不支持.closest方法的应用程序。

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();

所以我正在寻找.navPanel中的每个图像并遍历DOM并隐藏td它是否存在。有没有人知道是否有一个vanilla JavaScript函数我可以简单地添加到我的脚本中,填充缺少的.closest方法?

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?

感谢您的时间。

推荐答案

现代浏览器使用Element.closest()方法。

Modern browsers have the Element.closest() method.

示例:

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

参考:
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

您可以在此检查哪些浏览器具有内置支持:
https: //caniuse.com/#feat=element-closest

Here you can check which browsers have built-in support: https://caniuse.com/#feat=element-closest

当眉毛没有支撑时可以使用以下polyfill:
https://github.com/jonathantneal/closest

When there is no support in the browser the following polyfill could be used: https://github.com/jonathantneal/closest

这篇关于没有jQuery的Vanilla JavaScript .closest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆