没有jQuery找到最接近的元素 [英] Finding closest element without jQuery

查看:94
本文介绍了没有jQuery找到最接近的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在没有jquery的情况下找到具有特定标签名称的最近元素。当我点击< th> 时,我希望能够访问该表的< tbody> 。建议?我读过有关偏移的内容,但并没有真正理解它。我应该使用:

I am trying to find the closest element with a specific tag name without jquery. When I click on a <th> I want to get access to the <tbody> for that table. Suggestions? I read about offset but didn't really understand it too much. Should I just use:

假设已经设置为点击了元素

Assume th is already set to clicked th element

th.offsetParent.getElementsByTagName('tbody')[0]


推荐答案

参加派对的时间很少(非常),但仍然如此。这应该是技巧

Little (very) late to the party, but nonetheless. This should do the trick:

function closest(el, selector) {
    var matchesFn;

    // find vendor prefix
    ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
        if (typeof document.body[fn] == 'function') {
            matchesFn = fn;
            return true;
        }
        return false;
    })

    var parent;

    // traverse parents
    while (el) {
        parent = el.parentElement;
        if (parent && parent[matchesFn](selector)) {
            return parent;
        }
        el = parent;
    }

    return null;
}

这篇关于没有jQuery找到最接近的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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