Select specific closest element

magda picture magda · Nov 1, 2010 · Viewed 11.7k times · Source

I have the following html :

  <table id="objects">
    <tr>
        <td>
            <input type="text" value="2" />
        </td>
        <td>
            <a href="#" class="delete">link</a>
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" value="4" />
        </td>
        <td>
            <a href="#" class="delete">link</a>
        </td>
    </tr>    
  </table>

When I click anchor tag I'd like to select <input> closest to my link, and get it's value. How can I do this ? I was trying :

  $('.delete').click(function(e){
    e.preventDefault();
    var val = $(this).closest('input').attr('value');
    alert(val);
  });

but without any luck.

Answer

Gabriele Petrioli picture Gabriele Petrioli · Nov 1, 2010

If you look at the documentation for closest you will see that it says that it finds ancestors ..

Description: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

the input in your case is not an ancestor of the .delete link.

You need to move up with .closest('tr') and then drill down to find the input with .find('input')

so

var val = $(this).closest('tr').find('input').val();