Allen Liu
Allen Liu

Reputation: 4038

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.

Upvotes: 5

Views: 7486

Answers (4)

Scotty G
Scotty G

Reputation: 424

I know this is old but here is the fastest way ...

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

find() uses native browser methods, children() uses JavaScript interpreted by the browser

Upvotes: 0

Kevin B
Kevin B

Reputation: 95061

.closest only finds parents of the selected elements. Try this:

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

Update

changed to .children, the "> label" selector is depreciated.

Upvotes: 5

Highway of Life
Highway of Life

Reputation: 24431

Closest will begin at the current element and progress up the DOM tree, but because <label> is not a parent of your current element, you'll need to use 2 finds:

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

This is going to be your most efficient traversal.

Upvotes: 2

Jasper
Jasper

Reputation: 76003

.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();

Upvotes: 14

Related Questions