user3033997
user3033997

Reputation: 25

Selecting just one the closest element

I have problem with selecting just ONE the closest element by using jQuery.

My HTML code

<table>
    <tbody>
        <tr>        
            <td>
                <span class="control"><img class="doAction"></span>
            </td>
        </tr>   
        <tr>    
            <td class="details">sometext</td>
        </tr>
    </tbody>
</table>

I would like to get the text from the .details after clicking on the image .doAction

But the problem is that I have multiple times this same HTML code, so I want just the closest to this img .details text to get.

How can I do that?

Upvotes: 2

Views: 82

Answers (3)

Mr. Alien
Mr. Alien

Reputation: 157314

You can also use .parents() with .next() and .find()

$('.doAction').on('click', function() {
    console.log($(this).parents('tr').next().find('.details').text());
});

Demo

Over here, am selecting the parent tr of the img tag with a class of .doAction and then am moving on to the next tr and searching for an element with .details

Note that it's .parent(s), if you want you can also use .parent() but then you need to use it thrice, like

  $(this).parent().parent().parent().next().find('.details').text();
/*         --^--     --^--    --^--  --^--
  Selects   span      td        tr  goes to next tr and then finds for .details 
                                                            and returns text */

Upvotes: 1

user1017882
user1017882

Reputation:

$('.doAction').click(function(i, e)
{
    e.closest('table').find('.details').html();
});

NOTE: Another approach would be to traverse up to the tr only, get the next sibling, then get the .details from there. This may be more precise as you might have several of these .doAction and .details elements in there:

$('.doAction').click(function(i, e)
{
    e.closest('tr').next().find('.details').html();
});

Reference:

http://api.jquery.com/closest/

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

Use .closest() to traverse to table and then find td with .details in it:

 $('.doAction').click(function(){
   $(this).closest('table').find('.details').text();
 });

Upvotes: 0

Related Questions