Get the alt text of an img in each first <li>

Hi all,

I have several lists with images in each li

<article class="brand-details">
	<li class="largeImg"><img src="images/brands/charnos_1.jpg" alt="Hourglass" /><span></span></li>
	<li><a href="images/brands/charnos_1.jpg"><img src="images/brands/charnos_1small.jpg" alt="Hourglass"></a></li>
	<li><a href="images/brands/charnos_2.jpg"><img src="images/brands/charnos_2small.jpg" alt="Hourglass Blush corselette"></a></li>
	<li><a href="images/brands/charnos_3.jpg"><img src="images/brands/charnos_3small.jpg" alt="Superfit Black"></a></li>
	<li><a href="images/brands/charnos_4.jpg"><img src="images/brands/charnos_4small.jpg" alt="Belle Ivory"></a></li>

I want to populate each empty <span> in .largeImg (or preferably generate the span as well) with the alt text of img inside .largeImg in each list.

This populates each span with the alt text of the first image from the first list so I’m nearly there!

$(".brand-details ol li:nth-child(1)").children('span').text($(".brand-details ol li img").attr('alt'));

I always get stuck when more than one group of elements is involved!


jQuery will operate on everything in the set, but here you want to operate on the list items individually, so I would do it like this and pull them out one by one:

$(".brand-details ol li").each(function() {
  var li = $(this);
  //do your stuff here...

In this loop you do whatever you want to each li in turn. I’d be interested to see if anyone can offer a better solution.

Great stuff, I had to alter the selectors etc but this has done the trick…

$(".brand-details li:nth-child(1)").each(function(){
		var imgAlt = $(this).children('img').attr("alt");

Does that look right to you?

So, how would I go about creating the <span> with the content inside so I can avoid the empty spans?


Looks sensible. If you wanted to create the span programatically you could replace the Second line:


With something like:


This should make the span and populate it…

Brilliant! Thanks so much : )

No Problem :slight_smile:

As a point of style, can I also suggest that you do this on your first line…

var li = $(this);

…then work with the li variable rather than calling $(this) more than once. That way you’re only initialising one jQuery object in the loop. It’s a small point, but one that will benefit you if you have Many list items :slight_smile:

That sounds great, could you elaborate? I’m not sure I understand how I would alter it.

You might write:

$(".brand-details li:nth-child(1)").each(function(){
  var li = $(this);
  var imgAlt = li.children('img').attr("alt");

This way you’re only creating one jQuery object and storing it in a variable, rather than creating a new jQuery object on each line.

Ah that makes perfect sense. I thought you meant replace the first line with your suggestion so I was baffled!