views:

45

answers:

2

Trying to wrap an tag around an image, addClass and input src of img as href of tag:

 $(document).ready(function() {
$(".new img").each(function() {
    var src = $(this).attr('src').addClass('image');
    var a = $('<a/>').attr('href', src);
    $(this).wrap(a);
});
});

My HTML:

<img class="new" src="pic0.png" title="Image_Title"/>

Can't seem to get this to work. Any suggestions would be helpful!

+1  A: 

Your selector just needs an adjustment, this:

$(".new img")

Should be:

$("img.new")

The new class is on the <img> itself, the <img> isn't a descendant of a class="new" element, which is what your current selector is looking for. Also .attr('src') gets a string, so you need to add the class before calling it, overall like this:

$(function() {
  $("img.new").each(function() {
    var src = $(this).addClass('image').attr('src');
    var a = $('<a/>').attr('href', src);
    $(this).wrap(a);
  });
});

You can test it here, or a bit simpler/faster version here:

$(function() {
  $("img.new").each(function() {
    var a = $('<a/>').attr('href', this.src);
    $(this).addClass('image').wrap(a);
  });
});
Nick Craver
A: 

Two things. Firstly, you have your selector backwards -- it should be img.new. Secondly, attr returns a string, not jQuery, so you can't chain it. Do the following and it should work:

$(document).ready(function() {
    $("img.new").each(function() {
        var $this = $(this);
        var src = $this.attr('src');
        $this.addClass('image');
        var a = $('<a/>').attr('href', src);
        $this.wrap(a);
    });
});
lonesomeday
If I did this with a .click(function(), I'm thinking I should add unwrap in some way?
Mike