penguinstyles
penguinstyles

Reputation: 35

How can I use jQuery to automatically set unique alt tags for each image on page?

I am attempting to use jQuery to automatically set an alt tag on images without one. My images are displayed on the page like this:

<div class="thumbinner">
  <a href="#" class="image">
    <img alt="" src="#" class="thumbimage">
  </a>
  <div class="thumbcaption">Caption</div>
</div>

I've tried a couple of examples I've seen here on Stack Overflow, but I'm thoroughly confused on how to select the correct .thumbcaption text.

Any help would definitely be useful!

Upvotes: 1

Views: 49

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21638

$(function() {
  $('.thumbinner').each(function(){
    let thumbcaption = $(this).find('.thumbcaption').text();
    $(this).find('img').attr('alt', thumbcaption);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thumbinner">
  <a href="#" class="image">
    <img alt="" src="#" class="thumbimage">
  </a>
  <div class="thumbcaption">Caption</div>
</div>

Upvotes: 1

karthick
karthick

Reputation: 12176

You can use this code to set the captions on all the images inside thumbinner.

$('.thumbinner').each(function(){
   var caption = $(this).find('.thumbcaption').text();
   $(this).find('img').attr('alt', caption);
})

Upvotes: 0

Related Questions