McSimKammerer
McSimKammerer

Reputation: 13

jQuery: get child attribute

I have HTML like this:

<div>
    <a href="">sometext<img src="images/001.jpg" /></a>
    <a href="">sometext<img src="images/002.jpg" /></a>
    ...
    <a href="">sometext<img src="images/nnn.jpg" /></a>
</div>

All i want is make 'href' atrributes equal to 'src' attribute of child 'img' using jQuery. This is my unsuccessful attempt (no js-error, but without result):

$('div a').attr('href', $(this).children('img').attr('src'));

How i can get 'src' attribute of child 'img' for use like attr() second argument for parent 'a'?

Upvotes: 1

Views: 5925

Answers (3)

Manse
Manse

Reputation: 38147

You could loop each img and set the parent href attribute like this :

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

Working example here

Upvotes: 0

mgraph
mgraph

Reputation: 15338

Try this :

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

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

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

DEMO

Upvotes: 4

Related Questions