Search code examples
jqueryimagethishrefsrc

How to set image src using href from parent anchor?


I have the following link which is supposed to show an image within the link when javascript is loaded:

<a href="http://upload.wikimedia.org/wikipedia/commons/a/ae/Mad_scientist.svg" id="a">
 <img alt="no image">
</a>

The javascript is supposed to get the href property of the link and include it when writing the html for the image.

$('#a').html('<img src="' + $(this).attr('href') + '">image');

Somehow, $(this).attr('href') is returning undefined. What is wrong with this?

JsFiddle


Solution

  • DEMO

    $('#a').html(function () {
       return  '<img src="' + $(this).attr('href') + '">image'
    });
    

    A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.

    Refrence

    http://api.jquery.com/html/#html-functionindex--oldhtml

    http://learn.jquery.com/javascript-101/this-keyword/

    In your code

    $('#a').html('<img src="' + $(this).attr('href') + '">image');
    

    $(this) is undefined in your code.

    eg.

    $('#a').html(function () {
           return  '<img src="' + $(this).attr('href') + '">image'
    });
    

    In the above code this refers to current element i.e element with id="a"