daniyalahmad
daniyalahmad

Reputation: 3863

Change img src from parent anchor href

I have 150+ Links with internal image tag. Like this :

<a href="LINK1"><img src="LINK2" width="60" height="45" border="0"></a>

Now what i want is to image src LINK2 to LINK1 on page load. So the output will be :

<a href="LINK1"><img src="LINK1" width="60" height="45" border="0"></a>

My jQuery code so far :

$("img").attr("src",$("img").parent().attr("href"))

Thanks.

Upvotes: 1

Views: 150

Answers (2)

The Process
The Process

Reputation: 5953

For the attr src value, you can include function which will return href from the parent <a> for each image, this way you don't need to loop trough that img collection twice.

$("img").attr("src",function(){
    return $(this).parent('a').attr("href");
});

Upvotes: 1

cssyphus
cssyphus

Reputation: 40096

itsgoingdown is correct - you want to use a .each() fn to do this, but I would attack it the other way around:

$("a").each(function(){
    $(this).find('img').attr("src", $(this).attr("href") );
});

Upvotes: 1

Related Questions