Jquery: trying to make an image in a hyperlink

I'm almost where I want to be, other than I can't figure out how to turn var imgt into a hyperlink. I tried some things but it keeps returning [object] [Object]

$j('#hp-featured-item > div[id^="post-"]').each(function() {
      var id=this.id.match(/post-(\d+)/);
      var imgt = $j("img:eq(0)");

      // I tried this but it didn't work
      // var imgt = $j("<a href='/blog/?p="+id[1]+"'>"+$j("img:eq(0)")+"</a>");

      var pt = $j("p:not(:has(img)):eq(0)");
      var hh = $j("h2:eq(0)");
      $j(this).html('');
      $j(this).append(imgt).append(hh).append(pt);
}); 

      

/// Updated code

$j('#hp-featured-item > div[id^="post-"]').each(function() {
                var id=this.id.match(/^post-([0-9]+)$/);
                var imgt = $j("img:eq(0)");
                $j(imgt).wrap($j('<a>').attr('href', '/'));
                var pt = $j("p:not(:has(img)):eq(0)");
                var hh = $j("h2:eq(0)");
                $j(this).html('');
                $j(this).append(imgt).append(hh).append(pt);
        });

      

Ok, I put this in a comment, but I'll add it here as well based on your guess ... Basically, the original html output is very different in structure. Sometimes it

<img /> 
<h2> </h2> 
<p> </p>
<p> <img /> </p>
<h2> </h2>
<p> </p>

      

Sometimes it's just:

<h2> </h2>
<p><img /></p>
<p> text </p>

      

etc...

I want to transfer the first <img />

, first <h2>

and first <p>

(which is not wrapped around the image) and print them in the following order:

<img />
<h2>
<p>

      

And, the rest may just go away ... It's just a consolidated look ...

Ok, ok ... I added this to the bottom and it seems to work:

$j(this).each(function() {
                        var img = $j('img');
                        $j(img).wrap($j('<a>').attr('href', '/'));
                });

      

+2


source to share


1 answer


You can use jQuery.prototype.wrap for this:

$j('#hp-featured-item > div[id^="post-"]').each(function() {
      var id=this.id.match(/post-(\d+)/);
      var imgt = $j("img:eq(0)");

      $(imgt).wrap( 
          $('<a>').attr('href', '/blog/?p=' + id[1])
      );

});

      

This worked for me:



$('.post').each(function() {
    var img = $('img', this), src = $(img).attr('src')
    $(img).wrap( 
             $('<a>').attr('href', src)
    );
});

      

http://jsbin.com/iyabu

Make sure the href attribute you set is correct.

+4


source







All Articles