Bosc Bosc - 4 months ago 12
CSS Question

loop through divs and move hrefs to another div

I am trying to loop through

divs
take the
href
from one div and move it to the
href
of another div, and then repeat this for all the following divs.

I have it working so far as it does it for the first div but then it places that href link in all the others.

see https://jsfiddle.net/grmaw27y/5/

html:

<div class="container">
<div class="row">
<div class="col-md-4">
<div class="image">
<a href="#" class="">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=230%C3%97230&w=230&h=230" />
</a>
</div>
</div>
<div class="col-md-8">
<h2>Google</h2>
<div class="entry">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet ipsum eget odio maximus posuere. Fusce dapibus id urna quis eleifend. Nam lacinia consequat lectus, at ultricies purus elementum non.</p>
<p><a href="https://www.google.ie/">https://www.google.ie/</a></p>
</div>
</div>
</div>
</div>
<hr>
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="image">
<a href="">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=230%C3%97230&w=230&h=230" />
</a>
</div>
</div>
<div class="col-md-8">
<h2>Yahoo</h2>
<div class="entry">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
<p><a href="https://ie.yahoo.com/">https://ie.yahoo.com/</a></p>
</div>
</div>
</div>
</div>


js:

$('.entry').each(function() {
var href = $('.entry p a').attr('href');
$('.image a').attr('href', href);
});

Answer

Try this:

$('.entry').each(function(i,element) {
  var href = $(element).find('p a').attr('href');
  $(element).parent().prev().find('.image a').attr('href', href);
});

Working example: https://jsfiddle.net/grmaw27y/6/

So what was wrong with your code?

Your expression to find the href var href = $('.entry p a').attr('href'); and assign href $('.image a').attr('href', href);, were working on class selectors. which return array of all matches. In every pass they were matching the same two elements. To fix this we use the element object in loop, you specify exactly what you want to read and write.