Vinay
Vinay

Reputation: 237

How to get the closest img tag in jquery?

HTML

"+fileName+"

I need to change the image when the td with id=fileName is clicked in jQuery.

How can I fetch the img tag and change its src attribute using jQuery?

I am trying to do something like this :

$($(this).closest("img")).attr("src")

Upvotes: 4

Views: 10388

Answers (6)

Jeff Noel
Jeff Noel

Reputation: 7618

You could use .siblings()

JavaScript/jQuery

$(this).siblings("#img_id").children('img').prop('src');

Edit

JSFiddle proof

Upvotes: 4

pjdicke
pjdicke

Reputation: 329

You need to clean up your code a bit as you have a random <span> and the first <td> isn't closed. Your id's need to be wrapped in double quotes.

http://jsfiddle.net/pjdicke/tQ5vr/5/

<table>
   <tr class="test_file">
      <td id="img_id"><img src="http://www.abmuku.com/wp-content/uploads/2012/04/google-logo-small.jpg" /></td>
      <td colspan=2 id="fileName"><button>file name</button></td>
   </tr>
</table>

$('button').on('click', function(){
    $(this).closest('tr').find('td img').attr('src','http://atoralhistory.uconn.edu/images/Yahoo_logo_small.gif');
});

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55740

Use a combination of .closest and .find()

closest finds its ancestors

you need to find its descendants and not the ancestors

So you need to first find the closest row, which contains the filename id element and then find the img which is a descendant of the corresponding row

$(this).closest('tr').find("img").attr("src"); // using find

or

var $tr = $(this).closest('tr'); // get the closest row
$("img", $tr).attr("src");  // use a context to get the image

Upvotes: 8

michalzuber
michalzuber

Reputation: 5215

You have to replace the new_src variable.

$(function() {
   $('#fileName').on('click', function() {
      $(this).closest('tr').find('img').attr('src', new_src);
   });
});

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

Try with this

$(this).siblings().find('img').prop('src','your_image_url');

DEMO

Upvotes: 1

Travis J
Travis J

Reputation: 82267

"the td with id=fileName is clicked": You are going to have to go up to the tr element, and then use find to search through the descendants in order to find the image element. .parentNode will find the parent element of this (the <td> in this case). find("img") will find the image tag contained in the first td element.

$($(this.parentNode).find("img")).attr("src")

Upvotes: 2

Related Questions