Moving the DOM with jQuery.closest ()

What I thought was easy to .closest()process turned out to be wrong (or maybe I'm making a stupid mistake).

What I'm trying to do is access an element <label>from <div>with 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 be to try:

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

But he does not return anything.

+5
source share
3 answers

.closest()only looking for ancestor elements for initial selection. You need a combination of .closest()and .siblings()or .children():

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

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

Update

A very fast selector will use .prev()twice and .parent()as follows:

$('#start').parent().prev().prev();
+14
source

.closest . :

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

.children, "> label" .

+5

The closest will start from the current element and progress to the DOM tree, but since <label>it is not the parent of your current element, you will need to use 2 found files:

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

This will be your most effective workaround.

+2
source

All Articles