Liam
Liam

Reputation: 9855

Take href of an anchor in a container and apply it to image

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...

http://jsfiddle.net/fFgwb/


There will be multiple divs so I cant have the same id

Upvotes: 0

Views: 144

Answers (6)

Jacco
Jacco

Reputation: 3272

Okay, let's wrap it up:

  • you'll have several cards
  • each card contains two anchors
  • the first anchor should get the same href-value as the second anchor

Translated to jQuery:

$(".card-prod").each(function(){
    var anchors = $(this).find("a");
    anchors.eq(0).prop("href", anchors.eq(1).prop("href"));
});

Upvotes: 0

Ram
Ram

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

Josh Farneman
Josh Farneman

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

Starx
Starx

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

DarkAjax
DarkAjax

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

iambriansreed
iambriansreed

Reputation: 22241

Try:

$('img').each(function(){
    $(this).wrap('<a href="'+$(this).attr('src')+'"/>');
});

Just narrow that img selector, maybe with a class.

Upvotes: 0

Related Questions