Alvaro
Alvaro

Reputation: 41595

How to wrap a link to all images inside a div?

I have something like this:

<img class="photo" src="www.example.com" />
<img class="photo" src="www.example2.com" />
<img class="photo" src="www.example3.com" />

And I need to get this:

<a href="www.example.com" class="link">
    <img class="photo" src="www.example.com" />
</a>
<a href="www.example2.com" class="link">
    <img class="photo" src="www.example.com2" />
</a>
<a href="www.example3.com" class="link">
    <img class="photo" src="www.example.com3" />
</a>

I need to add the link, the href with the same code as the SRC of each image, and a class.

I was trying to do it like this:

$('.photo').wrapAll('<a>');

But it doesn't even work. What am I doing wrong?

Upvotes: 1

Views: 4579

Answers (3)

samccone
samccone

Reputation: 10926

$('img').wrap("<a href='foo'>") will work just fine.

Upvotes: 1

Tales
Tales

Reputation: 1923

Try this:

$('.photo').before('<a href="www.example3.com" class="link">');
$('.photo').after('</a>');

And if you want

$( '.photo' ).each( function() {
    var mySrc = $( this ).attr( "src" );
    $( this ).before( '<a href="' + mySrc + '" class="link">' ) );
    $( this ).after( '</a>' ) );
});

I hope this works for you...

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532435

Because the hrefs will all be different, you'll need to use each.

$('img.photo').each( function() {
    var $img = $(this),
        href = $img.attr('src');
    $img.wrap('<a href="' + href + '" class="link"></a>');
});

Note that wrapAll isn't what you want anyway as it will take all the elements and wrap them with a single anchor tag. If you weren't using an anchor that needs a different href for each element, wrap would work by itself and wrap each one individually.

Upvotes: 10

Related Questions