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

Trying to wrap a tag around an image, addClass and enter src from img as an href 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"/>

It doesn't seem to help. Any suggestions would be helpful!

+3
source share
2 answers

Two things. First, you have your selector back - it should be img.new. Secondly, it attrreturns a string, not jQuery, so you cannot concatenate 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);
    });
});
+9
source

Your selector just needs to be configured, this is:

$(".new img")

Must be:

$("img.new")

new <img>, <img> class="new", . , .attr('src') , , , :

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

/ :

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

Source: https://habr.com/ru/post/1772409/


All Articles