Aleksi
Aleksi

Reputation: 115

Copy image alt text and paste into div with jQuery

I have multiple images on page wrapped with div. I want to copy image alt text and paste it into next img-txt div.

<div class="container">
  <img src="kakka.jpg" alt="Text">
  <div class="img-txt"></div>
</div>

<div class="container">
  <img src="kakka2.jpg" alt="Text2">
  <div class="img-txt"></div>
</div>

Problem is that I get first alt text to everywhere. I know this is easy, but i can't get this working...

$(".container").each(function(i) {
  var alt = $("img").attr("alt");
  $(".img-txt").text(alt);
});

Upvotes: 2

Views: 1058

Answers (4)

SilverSurfer
SilverSurfer

Reputation: 4366

Here you got another way to copy the alt img into the div:

$("img").each(function(i) {
    $(this).next().html($(this).attr("alt"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <img src="kakka.jpg" alt="Text">
  <div class="img-txt"></div>
</div>

<div class="container">
  <img src="kakka2.jpg" alt="Text2">
  <div class="img-txt"></div>
</div>

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

The issue with your code is, traversing to correct sibling and then getting the alt text.

A smarter solution would be, using callback function of .text() along with traversing to sibling img element here:

$(".container .img-txt").text(function() {
   return $(this).siblings('img').attr("alt");
});

Working Demo

Upvotes: 5

kyun
kyun

Reputation: 10264

$(".container").each(function(i) {
  var alt = $(this).children('img').attr("alt");
  $(this).children('.img-txt').text(alt);
});

Try this.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

The issue is because you're selecting all the img and .img-txt elements in each iteration of the loop. Calling attr() on a collection of elements will only retrieve the attribute from the first element in that set.

You instead need to use the this keyword to reference the current element in the each() loop to find the elements within it:

$(".container").each(function() {
  var alt = $(this).find("img").prop("alt");
  $(this).find(".img-txt").text(alt);
});

You can however shorten this by providing a function to text() which is excuted against each matching element instance:

$(".container .img-txt").text(function() {
  return $(this).prev('img').prop('alt');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <img src="kakka.jpg" alt="Text">
  <div class="img-txt"></div>
</div>

<div class="container">
  <img src="kakka2.jpg" alt="Text2">
  <div class="img-txt"></div>
</div>

Upvotes: 3

Related Questions