How to get image id using jQuery?
29,754
Solution 1
$(img).load(function() {
var id = $(this).attr("id");
//etc
});
good luck!!
edit:
//suggested by the others (most efficient)
var id = this.id;
//or if you want to keep using the object
var $img = $(this);
var id = $img.attr("id")
Solution 2
Don't use $(this).attr('id')
, it's taking the long, inefficient route. Just this.id
is necessary and it avoids re-wrapping the element with jQuery and the execution of the attr() function (which maps to the property anyway!).
$(img).load(function() {
alert(this.id);
});
Solution 3
$(img).load(function() {
alert($(this).attr('id'));
});
![gautamlakum](https://i.stack.imgur.com/vHQqf.jpg?s=256&g=1)
Author by
gautamlakum
I help startups and enterprises go ahead with their digital products. Product Designer. Design Sprint Facilitator.
Updated on March 05, 2020Comments
-
gautamlakum over 4 years
I have written code like this.
<img id='test_img' src='../../..' />
I want to get the id of this image on image load like,
$(img).load(function() { // Here I want to get image id i.e. test_img });
Can you please help me?
Thanks.
-
gautamlakum over 13 yearsThanks to all. I think you all are correct. I tried all answers and all worked. Thanks to all of you.