views:

94

answers:

2

I'm trying to grab the href of one of my links and clone/copy that to the href of another link

Here's what i'm trying

      var link = $('.topbook');
      var link2 = $('.sidelink');
      var hrefOrig = link2.href;
      link.href = hrefOrig; 

Thanks

Jamie

UPDATE

Here's is what I'm trying to get

<a href="default.aspx?propid=BARN" class="topbook"></a>

The above link should clone the sidelink that has display:block

<a href="default.aspx?propid=FARM" class="sidelink" style="display:none"></a>

<a href="default.aspx?propid=BARN" class="sidelink" style="display:block"></a>

Hope this helps

+4  A: 

Try with attr like this:

 var link = $('.topbook');
 var link2 = $('.sidelink');
 var hrefOrig = link2.attr('href');
 $(link).attr('href', hrefOrig); 

You can make it shorter like this:

$('.topbook').attr('href', $('.sidelink').attr('href')); 

Update

To get the href of visible elements, you can use the :visible filter selector like this:

$('.topbook:visible').attr('href', $('.sidelink').attr('href')); 

This will apply the href to those elements that have class topbook and are visible/showing.

Sarfraz
Can't seem to get that to work :\
Jamie Taylor
@Jamie Taylor: Can you elaborate exactly what are you expecting?
Sarfraz
@Sarfraz see my update thanks
Jamie Taylor
@Jamie: Try this: `$('.topbook').attr('href', $('.sidelink:visible').attr('href'));`
Sarfraz
@Sarfraz: I tried that but for some reason that doesn't work either
Jamie Taylor
A: 

It is by the way much faster if you use $() with tag names, as this query can be internally optimized via document.getElementByTagName()

var link = $('a.topbook');
var link2 = $('a.sidelink');
link.attr('href',link2.attr('href'));

and if you even know, that there is only one link each:

var link = $('a.topbook:first');
var link2 = $('a.sidelink:first');
link.attr('href',link2.attr('href'));
haggi
Thanks that works - bit of a problem is there any way to say get the href of the ".topbook" button that has the style ="display:block" property? As i have 10 buttons with the class ".topbook" and only want to get the href of the button that is showing. Thanks
Jamie Taylor