André Martins André Martins - 4 months ago 18
Javascript Question

Get all ALT tags

I want to get the alt tags of each image inside a div and list them in a

<ul><li>
, but I don't want repeated alts. For example, if 2 imgs have the alt "example1", I want it listed only one time on my
<ul><li>
.

My current code:

JS

$('.img-produto > img').each(function(){
$('.filters').append('<li>'+ $(this).attr('alt') +'</li>');
});


HTML

<ul class="filters"></ul>
<div class="img-produto">
<img src="img link" alt="example1" />
<img src="img link" alt="example1" />
</div>


Thanks!

Answer

Need to create collection of unique alt values and check that before appending anything

var alts = {};
$('.img-produto > img').each(function(){
  var alt = $(this).attr('alt');
  if(!alts[alt]){
      alts[alt] = true;
      $('.filters').append('<li>'+ alt  +'</li>');
  }     
});
Comments