Question

I want to convert all images like this:

<img src='example.com/img1.jpg' />
<img src='example.com/img2.jpg' />
<img src='example.com/img3.jpg' />

to:

<a href='example.com/img1.jpg' rel='shadowbox[Mixed]'><img src='example.com/img1.jpg' /></a>
<a href='example.com/img2.jpg' rel='shadowbox[Mixed]'><img src='example.com/img1.jpg' /></a>
<a href='example.com/img3.jpg' rel='shadowbox[Mixed]'><img src='example.com/img1.jpg' /></a>

with jQuery, I tried this:

$("img").replaceWith( "<a rel='shadowbox[Mixed]' href='"+$(this).attr("src")+"'><img src='" + $(this).attr("src") + "'/></a>" );

but not worked :(

Was it helpful?

Solution

Try wrap

$("img").wrap(function(){
    return "<a rel='shadowbox[Mixed]' href='"+$(this).attr("src")+"'></a>";
});

DEMO

OTHER TIPS

$('img').each(function(k,v) {
    $(this).wrap('<a href="' + $(this).prop('src') + '" rel="shadowbox[Mixed]" />');
});

Here you go (however, you would probably want to use @Musa's .wrap() solution which is much more elegant):

$(document).ready(function() {

    $('img').each(function() {
         var attr = $(this).attr('src');
         var newElement = "<a href='" + attr + "' rel='shadowbox[Mixed]'><img src='" + attr + "' /></a>"

         $(newElement).insertAfter($(this));
         $(this).remove();

    });     

});

DEMO jsFiddle: http://jsfiddle.net/9DUGH/1/

A useful read: .insertAfter()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top