使用jQuery .closest()遍历DOM

时间:2012-02-23 21:15:00

标签: jquery jquery-selectors closest

我认为.closest()处理的问题很简单(或许我犯了一个愚蠢的错误)。

我要做的是访问<label>中带有内部文字的<div>元素:I AM HERE

<li>
    <label>I WANT TO ACCESS THIS ELEMENT</label>
    <div>...</div>
    <div>
        <input/>
        <input/>
        <input/>
        <div id="start">I AM HERE</div>
    </div>
</li>

我的第一个猜测是尝试这个:

$('#start').closest('label') 

但它不会返回任何东西。

4 个答案:

答案 0 :(得分:14)

.closest()仅查找初始选择的祖先元素。您需要.closest().siblings().children()的组合:

//find closest parent `<li>` element and then find that element's child `<label>` element
$('#start').closest('li').children('label');

//find the closest parent `<div>` element and then find that element's sibling `<label>` element
$('#start').closest('div').siblings('label');

更新

一个非常快的选择器是使用.prev()两次和.parent()这样:

$('#start').parent().prev().prev();

答案 1 :(得分:5)

.closest仅查找所选元素的父级。试试这个:

$("#start").closest("li").children("label");

<强>更新

已更改为.children"> label"选择器已弃用。

答案 2 :(得分:2)

Closest将从当前元素开始并向前推进DOM树,但由于<label>不是当前元素的父元素,因此您需要使用2个查找:

 $('#start').closest('li').children('label');

这将是您最有效的遍历。

答案 3 :(得分:0)

我知道这很旧,但这是最快的方法...

$('#start').closest('li').find('label');

find()使用本机浏览器方法,children()使用浏览器解释的JavaScript