xZ6a33YaYEfmv
xZ6a33YaYEfmv

Reputation: 1816

jQuery insertBefore, insertAfter problem

I want to make my images as links with help of jQuery:

 $("img:gt(0)").each(function () {
            var curr = $(this);
            if (curr.width() >= 500) {
                var m = 500 / curr.width();
                curr.height(curr.height() * m);
                curr.width(curr.width() * m);
            }
            $("<a href='" + curr.attr("src") + "'>").insertBefore(curr);
            $("</a>").insertAfter(curr);
        });

But I'm getting:

<a href="/Images/7827-1280x800.jpg"></a>
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">

Instead of:

<a href="/Images/7827-1280x800.jpg">
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">
</a>

Upvotes: 1

Views: 1744

Answers (3)

Serhiy
Serhiy

Reputation: 4507

It's because $("<a href='" + curr.attr("src") + "'>") will create a common html element. I think, jQuery will ignore missing closing tag and create this html: <a href="/Images/7827-1280x800.jpg"></a> and $("</a>") will be ignored at all.

Upvotes: 1

Daniel
Daniel

Reputation: 5024

You could use the wrap() method provided by jQuery

$("img:gt(0)").each(function () {
    var curr = $(this);
    if (curr.width() >= 500) {
        var m = 500 / curr.width();
        curr.height(curr.height() * m);
        curr.width(curr.width() * m);
    }
    curr.wrap($('<a href="' + curr.attr("src") + '">'));
});

Upvotes: 1

rahul
rahul

Reputation: 187030

You don't have to do like this. You can use wrap to do this.

Something like

curr.wrap("<a href='" + curr.attr("src") + "' />");

Upvotes: 2

Related Questions