Ali Najm Ali Najm - 26 days ago 5
Javascript Question

How to get unique images alt using jquery?

I'm trying to get Images alt inside div

the problem is, i have a similar outputs text, from first image alt!

How can we fix it?

var images = $('.box img').attr('alt');
$( ".box .img-block" ).text(images).attr("data-title", images);



<img src="img1.jpg" alt="Text 1">
<div class="img-block"></div>


<img src="img2.jpg" alt="Text 2">
<div class="img-block"></div>

<img src="img3.jpg" alt="Text 3">
<div class="img-block"></div>


Result

<img src="img1.jpg" alt="Text 1">
<div class="img-block">Text 1</div>

<img src="img2.jpg" alt="Text 2">
<div class="img-block">Text 1</div>

<img src="img3.jpg" alt="Text 3">
<div class="img-block">Text 1</div>


thanks

Answer

jQuery(document).ready(function($){
   $('.box').each(function () {
     $(this).find('.img-block').text($(this).find('img').attr('alt'));
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img src="img1.jpg" alt="Text 1">
<div class="img-block"></div>
</div>

<div class="box">
<img src="img2.jpg" alt="Text 2">
<div class="img-block"></div>
</div>

<div class="box">
<img src="img3.jpg" alt="Text 3">
<div class="img-block"></div>
</div>

<div class="box">
<img src="img4.jpg" alt="Text 4">
<div class="img-block"></div>
</div>