Search code examples
javascriptjqueryhtmlhref

Get href from one link and clone to another href


I'm basically trying to get the href from one link and then have that populate into another:

HTML:

<a href="somelinkthing.com" class="main-link">Link to thing</a>
<a class="second-link">Link to duplicate</a>

SCRIPT:

$('.main-link').attr('href', $('.second-link').attr('href')); 

Trying to get the href from .main-link to populate to .second-link so it should become this:

OUTPUT:

<a href="somelinkthing.com" class="main-link">Link to thing</a>
<a href="somelinkthing.com" class="second-link">Link to duplicate</a>

Not sure if I have something backwards, but I am not all with it right now so that could be it too.


Solution

  • Your code is setting the href attribute of .main-link rather than .second-link - you need to target the element you want to change:

    $('.second-link').attr('href', $('.main-link').attr('href'));