Traversing the DOM with jQuery .closest()

Allen Liu picture Allen Liu · Feb 23, 2012 · Viewed 7.4k times · Source

What I thought would be an easy one for .closest() to handle turned out not to be (or perhaps I am making a silly mistake).

What I am trying to do is access the <label> element from the <div> with the inner text: 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>

My first guess would have been to try this:

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

But it does not return anything.

Answer

Jasper picture Jasper · Feb 23, 2012

.closest() only looks for ancestor elements to the initial selection. You want a combination of .closest() and .siblings() or .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');

Update

A very fast selector would be to use .prev() twice and .parent() like this:

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