coder
coder

Reputation: 301

Wrap existing link from HTML around other images?

How to clone an existing link with class="link" and wrap it around each img in the div "wrap"? Suppose we don't know the link so we can't just use this method:

$('#wrap img').wrap('<a href="http://foo.com"></a>');

HTML:

<a href="http://foo.com" class="link">
    <img/>
</a>
<div id="wrap">
    <img class="img" />
    <img class="img" />        
    <img class="img" />
</div>

Result:

<a href="http://foo.com" class="link">
    <img/>
</a>
<div id="wrap">
      <a href="http://foo.com" class="link"><img class="img" /></a>
      <a href="http://foo.com" class="link"><img class="img" /></a>    
      <a href="http://foo.com" class="link"><img class="img" /></a>
</div>

Upvotes: 1

Views: 234

Answers (4)

Oguzhan ARSLAN
Oguzhan ARSLAN

Reputation: 1

Image dimensions in then created this is called into the picture if the picture is not loaded error image is shown.

<div id="hekimResimMini"><img src="" id="imgHekimResim" alt="" width="40" height="55" ></div>


    $('#imgHekimResim').load(function(){})
    .attr("src", "./personelResimi.jpeg?kurSicNo="+lcd.list[x].DOKTORID)
    .error(function() { 
        var thisImg = this;
        if ( $.browser.msie ) {
           setTimeout(function() {
              if ( ! thisImg.complete ) {
                 $(thisImg).attr('src', '../../images/error.png');
                 $(thisImg).css('width','40').css('height','27').css('margin-top','14px').css('margin-bottom','14px');
              }
           },250);
        } else {
           $(this).attr('src', '../../images/error.png');
           $(thisImg).css('width','40').css('height','27').css('margin-top','14px').css('margin-bottom','14px');
        }
    });

Upvotes: 0

AmanVirdi
AmanVirdi

Reputation: 1685

You can simply try this single line:

$('#wrap img').wrap('<a href="' + $('a.link').prop('href') + '">');

To clone the element without children:

$('#wrap img').wrap($('a.link').clone().empty());

Upvotes: 1

Ram
Ram

Reputation: 144659

You could use the outerHTML property:

var link = $('.link').clone().empty().prop('outerHTML');
$('#wrap img').wrap(link);

Upvotes: 1

AlexL
AlexL

Reputation: 1707

Do this:

var anchor = $(".link");
anchor.html('');
$("#wrap img").wrap(anchor);

Upvotes: 1

Related Questions