如何查找包含特定选择器的父元素

4
假设有以下HTML结构(1):
$('.child')元素,我可以访问$('.gran-parent')元素,类似于$('.child').parent().parent();
但我认为这不是一个好的方式,因为它不够通用。
假设在$('.gran-parent')和$('.child')之间有其他divs。
$('.child')开始,最通用的方法是指向第一个class为gran-parent的父元素是什么?
<div class='gran-parent'>
    <div class='parent'>
        <div class='child'>
        </div>
    </div>
</div>
2个回答

5

你希望:

$('.child').closest(".grand-parent");

.closest会一直向上遍历直到找到一个.grand-parent元素。你也可以使用.parents(".grand-parent"),但这可能会返回多个结果,取决于您的DOM层次结构,因此您需要执行以下操作:

.parents(".grand-parent").eq(0)

或者:

.parents(".grand-parent").slice(0)

或者:

.parents(".grand-parent:first")

所有这些方法都没有 .closest() 方法优雅。

请参见:


2
你正在寻找.parents()运算符。
例子:
$('.child').parents('.gran-parent');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接