JQuery - copy dynamic link from one element to another
The url in div.alpha is dynamic. I need to take this url and apply it to the 'a href' that wraps the 'View Details' in a div.beta p>
<div class="alpha">
<a href="http://www.url.com">Example</a>
Plus some other stuff which may contain links, etc
that I don't want to copy to the other div.
</div>
<div class="beta">
View Details
</div>
Desired output:
<div class="alpha">
<a href="http://www.url.com">Example</a>
Plus some other stuff which may contain links, etc
that I don't want to copy to the other div.
</div>
<div class="beta">
<a href="http://www.url.com">View Details</a>
</div>
I can get the link like this: $('.alpha').find('a').attr('href');
But I don't know how to pass this link to XXXX below:
$('.beta').each(function(){
$(this).text($(this).text().replace('View Details', '<a href="XXXX">View Details</a>'));
});
+3
source to share
4 answers
You can clone a.alpha
and then just paste the .b
content:
// clone the link, remove the text
$link = $('.alpha').find('a').clone().text('');
// wrap all .beta contents with the cloned link
$('.beta').contents().wrap($link);
Here's a violin
+2
source to share
You can achieve the result by updating your code to the following.
var href = $('.alpha').find('a').attr('href'); // get href of anchor
var text = $('.beta').text(); // get text of beta element i.e. View Details
var betaHTML = "<a href='" + href + "'>" + text + "</a>"; // Create anchor
$('.beta').html(betaHTML); // Update beta element
+1
source to share
If you have multiple elements div.alpha
and div.beta
then the best way to achieve this - it also works for one pair - is:
$('div.beta').html(function(i,html) {
return $(this).prev('div.alpha').find('a').clone().html( html );
});
$('div.beta').html(function(i,html) {
return $(this).prev('div.alpha').find('a').clone().html( html );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pair">
<div class="alpha">
<a href="http://www.url.com">Example 1</a>
</div>
<div class="beta">
View Details
</div>
</div>
<div class="pair">
<div class="alpha">
<a href="http://www.example.com">Example 2</a>
</div>
<div class="beta">
View Details
</div>
</div>
0
source to share