Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap <a> tags around <img /> with href = img src?

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!

like image 318
Macsupport Avatar asked Oct 31 '10 23:10

Macsupport


People also ask

Can you wrap image in a tag?

Think of an a tag as a box that wraps the element. you can think of it as an invisible border around and including everything within. if you wrap an image in an a tag the image is clickable, it will direct you to the href of the a tag. So if you want the image to click to the source of the image.

How do you wrap an image in an anchor in HTML?

To create an image link, you combine an <a> tag (i.e. link) with an <img> tag (i.e. image). You simply "wrap" the link code around the image code.


2 Answers

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);
    });
});
like image 66
lonesomeday Avatar answered Oct 06 '22 08:10

lonesomeday


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);
  });
});
like image 27
Nick Craver Avatar answered Oct 06 '22 08:10

Nick Craver