Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 367
Vinay Avatar asked Oct 26 '25 07:10

Vinay


1 Answers

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
like image 60
Sushanth -- Avatar answered Oct 27 '25 22:10

Sushanth --