Wesley
Wesley

Reputation: 5621

JQuery complicated selector issue

Should be easy. I'm adding a button to each table row, that gets information out of a number of table cells in that row.

<tr>
  <td><img src='targetInfo' /></td>
  <td></td>
  <td>
    <div>CLICKED ELEMENT</div>
  </td>
</tr>

I would expect:

this: $(this).closest('tr td:eq(0) img').attr('src'); or

this: $(this).closest('tr>td:eq(0)>img').attr('src');

to work, but neither is working properly.

Currently I'm having to use the below, which seems sub-optimal. What am I missing in my selector?

$(this).closest('tr').children('td:eq(0)').children('img').attr('src');

Upvotes: 1

Views: 376

Answers (3)

MetalFrog
MetalFrog

Reputation: 10533

I've done something similar recently. I just used parent and first-child.

$(this).closest('tr').find('td:first-child img').attr('src')

Upvotes: 0

jmar777
jmar777

Reputation: 39649

Your current working solution is the best approach (or something similar to it, such as):

$(this).closest('tr').children('td:eq(0) > img').attr('src');

For this problem you won't be able to avoid having to crawl up the tree and then back down. Several ways to accomplish that, but not within a single selector.

Upvotes: 2

mgraph
mgraph

Reputation: 15338

try:

$(this).closest('tr').find('td').eq(0).find('img').attr('src');

or:

 $(this).closest('tr').find('td:first').find('img').attr('src');

Upvotes: 1

Related Questions