Reputation: 9855
I have a list of DIV's that all contain a piece of text, an image, and an anchor.
With Javascript/jQuery, is it possible to take the href of the anchor, and wrap the image in anchor tags with that link?
I know this is a strange requet, Ive made a fiddle...
There will be multiple divs so I cant have the same id
Upvotes: 0
Views: 144
Reputation: 3272
Okay, let's wrap it up:
Translated to jQuery:
$(".card-prod").each(function(){
var anchors = $(this).find("a");
anchors.eq(0).prop("href", anchors.eq(1).prop("href"));
});
Upvotes: 0
Reputation: 144689
you should add classes like .divs to divs and other classes to anchor links:
$(document).ready(function(){
$(".divs").each(function(){
$(this).find("a").hasClass("anchor").attr("href", $(this).find("a").hasClass("continue").attr('href'))
});
});
Upvotes: 0
Reputation: 1739
With jQuery:
$('.card-prod').each(function () {
var that = $(this),
imgA = that.find('a img').parent(),
newHref = that.find('a').not(imgA).attr('href');
imgA.attr('href', newHref);
});
Upvotes: 0
Reputation: 78981
Here is a way
var src = $("#imgid").attr("src"); //take out the src
$("#imgid").wrap($('<a href="'+src+'" />'); //wrap around it with the anchor
Your usage, can be something like
$("img", $("#divid")).each(function() {
var src = $(this).attr("src"); //take out the src
$(this).wrap($('<a href="'+src+'" />')); //wrap around it with the anchor
});
Here is a demo with this implementation on your fiddle.
Upvotes: 1
Reputation: 16223
If i got what you want correctly, you can do it with something like:
$('a').attr('href', function() {
return $(this).find('img').attr('src');
});
As you can see here.
Upvotes: 0
Reputation: 22241
Try:
$('img').each(function(){
$(this).wrap('<a href="'+$(this).attr('src')+'"/>');
});
Just narrow that img
selector, maybe with a class.
Upvotes: 0