S.Hagvin S.Hagvin - 2 years ago 76
Javascript Question

How can I create function which will return value of jQuery method attr

I have html structure:

<li><img src="img/product1.png" alt="product1"></li>
<li><img src="img/product2.png" alt="product2"></li>
<li><img src="img/product3.png" alt="product3"></li>
<li><img src="img/product4.png" alt="product4"></li>

and I have done attempt create function which will get attribute of current img element and I want to return from this function this current attribute, I have next code:

var sr = "";
function imgSrc(){
$('div').on("click", "ul li img", function () {
sr = $(this).attr("src");
return sr;


unfortunately I get undefined in my console.

Answer Source

Your function doesn't return anything. It just defines an onClick handler. So that's why you get a return value of 'undefined'

If your intention is to log the src of a div when you click on it, your code would need to be more like this...

$('div').on("click", "ul li img", function () 
    var sr = $(this).attr("src");

That registers the event listener on the element.

However, if you want to wrap the listener in a function and then call that function, as you have done, that will also work - the function in the on("click") will be triggered when clicking an element. The value of sr will be set, but the outer function itself won't return a value. You would need to find another way to do something with the value of sr, within the function in the on("click")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download