Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing the DOM with jQuery .closest()

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.

like image 967
Allen Liu Avatar asked Feb 23 '12 21:02

Allen Liu


1 Answers

.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();
like image 171
Jasper Avatar answered Sep 27 '22 18:09

Jasper