Question

I'm nearly where I want to be, except that I can't figure out how to turn var imgt into a hyperlinked image. I've 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 it in the comment, but I'll put it here too based on your suggestion... Essentially, the original html output varies greatly in structure. Sometimes it's

<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 pull the first <img />, the first <h2>, and the first <p> (that isn't wrapped around an image) and print them out in that order:

<img />
<h2>
<p>

And, the rest can just go away... It's just a summary view...

Well, 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', '/'));
                });
Was it helpful?

Solution

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 it to is right.

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