Search code examples
jqueryjquery-selectorsclosest

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.


Solution

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