首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在没有jQuery的情况下查找最近元素

在没有jQuery的情况下查找最近元素
EN

Stack Overflow用户
提问于 2013-09-07 02:06:51
回答 11查看 101.7K关注 0票数 92

我正在尝试查找具有特定标记名但没有jquery的最接近的元素。当我单击一个<th>时,我想要访问该表的<tbody>。有什么建议吗?我读过关于offset的文章,但并不是很了解它。我应该只使用:

假设已将th设置为已单击的th元素

代码语言:javascript
复制
th.offsetParent.getElementsByTagName('tbody')[0]
EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2014-06-08 23:13:55

在聚会上有点(非常)晚了,但尽管如此。这应该会完成trick

代码语言:javascript
复制
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;
}
票数 71
EN

Stack Overflow用户

发布于 2013-09-07 02:11:06

下面是如何在不使用jQuery的情况下通过标记名获得最接近的元素:

代码语言:javascript
复制
function getClosest(el, tag) {
  // this is necessary since nodeName is always in upper case
  tag = tag.toUpperCase();
  do {
    if (el.nodeName === tag) {
      // tag name is found! let's return it. :)
      return el;
    }
  } while (el = el.parentNode);

  // not found :(
  return null;
}

getClosest(th, 'tbody');
票数 22
EN

Stack Overflow用户

发布于 2014-11-18 23:07:19

代码语言:javascript
复制
function closest(el, sel) {
    if (el != null)
        return el.matches(sel) ? el 
            : (el.querySelector(sel) 
                || closest(el.parentNode, sel));
}

这个解决方案使用了HTML5规范的一些新特性,并且在旧的/不兼容的浏览器(阅读: Internet Explorer)上使用它将需要polyfill。

代码语言:javascript
复制
Element.prototype.matches = (Element.prototype.matches || Element.prototype.mozMatchesSelector 
    || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector 
    || Element.prototype.webkitMatchesSelector || Element.prototype.webkitMatchesSelector);
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18663941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档