tags:

views:

24

answers:

2

Hi

I have the following html markup:

<div class='photoset'>  
<a href="foo-01.html"><img src="foo-01.jpg" /></a>  
<a href="foo-02.html"><img src="foo-02.jpg" /></a>  
<a href="foo-03.html"><img src="foo-03.jpg" /></a>  
<a href="foo-04.html"><img src="foo-04.jpg" /></a>  
</div>

I want to manuipulate the DOM so that the src value of each image replaces the href value of the parent link element, so that the markup becomes:

<div class='photoset'>  
<a href="foo-01.jpg"><img src="foo-01.jpg" /></a>  
<a href="foo-02.jpg"><img src="foo-02.jpg" /></a>  
<a href="foo-03.jpg"><img src="foo-03.jpg" /></a>  
<a href="foo-04.jpg"><img src="foo-04.jpg" /></a>  
etc...
</div>

Why ever would I want to do this, you ask? I'm pulling images into a page using the Flickr API, but then wish to use the jQuery ColorBox plugin for a gallery effect...and for that I believe I need to render the Flickr-generated markup as above.

Thanks in advance

Andrew

+2  A: 

Like this:

$('a:has(img)').attr('href', function() {
    return $(this).find('img').attr('href');
});
SLaks
+1 That's maybe not as fast as @patrick's, but it's more idiomatic w/r/t jQuery. :) And the speed difference would not be noticeable anyway.
Tomalak
I'd agree with @Tomalak. The likely imperceptible performance difference in my answer could easily take a backseat to a coding style preference.
patrick dw
Thanks SLaks! Your contribution is very much appreciated!
arsmith771
+3  A: 
$('.photoset a > img').each(function() {
    this.parentNode.href = this.src;
});

This iterates over images that are a child of <a> and are contained in .photoset, and sets the href property of its parentNode to the value of its src.

patrick dw
+1 That's very probably faster than @Slaks' version.
Tomalak
@patrick what does a > img means , i work in jquery , but i never used that symbol , can you explain that.
gov
@gov - It is [a child selector](http://api.jquery.com/child-selector/) and is a way of limiting the selection to only direct children of the parent. Not terribly important here, since the nesting doesn't go any deeper, but can improve efficiency in other cases.
patrick dw
@patrick, Thank you very much.
gov
@gov - You're welcome. :o)
patrick dw
Thanks patrick dw! Works a treat, and so syntax-economic! Thanks also Tomalak for participating.
arsmith771
@arsmith771 - You're very welcome. :o)
patrick dw