Reputation: 1816
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
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
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