How can i get the src of the <img> inside a dynamic(jquery-created) element?

Viewed 36
$("#grid").on("click", $("#grid > .items > img"), function () {
  alert($(this).css("src"));
});

grid is the parent.i need to get the src of the clicked items's img.

2 Answers

Few issues here:

  1. Your event delegation syntax is not correct. Instead of passing jQuery object you can simply pass a string.
  2. Also, in selector you don't need to pass #grid again, as it already points to the parent container when you use: $("#grid").on("click", ...
  3. Also, .css(propertyName) is used to get the value of a computed style property for the first element in the set of matched elements, but here you are not looking for any style property but you are looking for the src attribute of an element. So, you need to use .attr(attributeName) method here instead, as it gets the value of an attribute for the first element in the set of matched elements.

So, your updated code will look like:

$("#grid").on("click", ".items > img", function() {
  alert($(this).attr("src"));
});

You should actually access the src of an img attribute. So it would be like:

alert($(this).attr("src"));
Related