ccmanz
ccmanz

Reputation: 181

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

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?

Upvotes: 2

Views: 28

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337620

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>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370929

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>

Upvotes: 1

Related Questions