Reputation: 13
As the title says, I am having some issues converting images to links using jquery. My code right now is:
var all_img = $(".message .content").find("img");
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith($("<a href='" + src +"'>Image " + index+1 + "</a>"));
});
Which results in the images being replaced with [object Object]
. I have also tried:
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
Which results in the html I am trying to insert going in as plain unclickable text. Am I misunderstanding how .replaceWith()
works?
Upvotes: 1
Views: 52
Reputation: 67505
You couldn't call the jQuery .replaceWith()
method on value
, you need to use a jQuery object, to target the current img in every iteration you need to use $(this)
like :
all_img.each(function (index, value) {
var src = value.src;
$(this).replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
Upvotes: 5
Reputation: 15831
I think it is better to create a new element and remove/hide the img:
$('.turnInAnchor').click(function(e){
$('img').each(function(index, el) {
$('body')
.append("<a href='"+el.src+"' target='_blank'>Image "+index+"</a>");
el.remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="turnInAnchor">Turn in anchor</button>
<img src="https://upload.wikimedia.org/wikipedia/it/7/75/Twin_Peaks_Episodio_Pilota_Laura_Palmer.png" />
Upvotes: 0