use jquery each to transfer link and assign it to new element

Viewed 22

I'm kind confused on how to use jquery each store value from link then assign it new to link element.

Here's the markup.

<div class="box">
<a href="linkhere">Title</a>
<a href="transferhere" class="mybtn">New Link</a>
</div>

<div class="box">
<a href="linkhere">Title</a>
<a href="transferhere" class="mybtn">New Link</a>
</div>

<div class="box">
<a href="linkhere">Title</a>
<a href="transferhere" class="mybtn">New Link</a>
</div>

Here's what I did

$(".box").each(function(){
        var hyperLinkValue = $('.box > a').attr('href');
        $('a.mybtn').attr("href", hyperLinkValue);
});

but it doesn't seem to work?. Any thoughts?

2 Answers

Rather than iterating over the .boxes, iterate over the first child of the .boxes. Then, referencing this inside the handler will get you to the linkheres, and calling .next() on it will get you to the transferlinkhere:

$('.box > :first-child').each(function() {
  $(this).next().prop(
    'href',
    this.href
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <a href="linkhere">Title</a>
  <a href="transferhere" class="mybtn">New Link</a>
</div>

<div class="box">
  <a href="linkhere">Title</a>
  <a href="transferhere" class="mybtn">New Link</a>
</div>

<div class="box">
  <a href="linkhere">Title</a>
  <a href="transferhere" class="mybtn">New Link</a>
</div>

Your current logic is selecting every a and .mybtn element in the DOM within each iteration of the loop. To fix this you should use the this keyword to reference the element in the current iteration of the each() loop only:

$(".box").each(function() {
  var hyperLinkValue = $(this).find('a').attr('href');
  $(this).find('a.mybtn').attr("href", hyperLinkValue);
});

That being said, you can simplify the logic providing a function to attr() which returns the value to set:

$("a.mybtn").attr('href', function() {
  return $(this).prev('a').attr('href');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <a href="linkhere">Title</a>
  <a href="transferhere" class="mybtn">New Link</a>
</div>

<div class="box">
  <a href="linkhere">Title</a>
  <a href="transferhere" class="mybtn">New Link</a>
</div>

<div class="box">
  <a href="linkhere">Title</a>
  <a href="transferhere" class="mybtn">New Link</a>
</div>

Related