找到最近的具有特定类的祖先元素 [英] Find the closest ancestor element that has a specific class

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

问题描述

如何在纯 JavaScript 中找到离具有特定类的树最近的元素的祖先?例如,在这样的树中:

<div class="近祖先"><p>我在哪里?</p>

然后我想要 div.near.ancestor 如果我在 p 上尝试这个并搜索 ancestor.

解决方案

更新:现在支持在大多数主要浏览器中

document.querySelector("p").closest(".near.ancestor")

注意这可以匹配选择器,而不仅仅是类

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

<小时>

对于不支持 closest() 但有 matches() 的旧浏览器,可以构建类似于@rvighne 的类匹配的选择器匹配:

function findAncestor (el, sel) {while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));返回 el;}

How can I find an element's ancestor that is closest up the tree that has a particular class, in pure JavaScript? For example, in a tree like so:

<div class="far ancestor">
    <div class="near ancestor">
        <p>Where am I?</p>
    </div>
</div>

Then I want div.near.ancestor if I try this on the p and search for ancestor.

解决方案

Update: Now supported in most major browsers

document.querySelector("p").closest(".near.ancestor")

Note that this can match selectors, not just classes

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


For legacy browsers that do not support closest() but have matches() one can build selector-matching similar to @rvighne's class matching:

function findAncestor (el, sel) {
    while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
    return el;
}

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

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