Ian
Ian

Reputation: 3

JQuery to see if image alt tag is in variable array and then add class

I have an html grid of images. I want to use JQuery to add HTML to all images that have an alt tag that match items from a list, or array.

There are varies posts about using JQuery to add a class to html if a specific alt tags are found, but I'm trying to do this with a list of alt tags. I can make it work if I only have one value in the variable. How do I make it work with a whole list of values for alt tags?

<main class="grid">
<div><img src="/images/image_1.jpg" alt="1904380_ORAN"></div>
<div><img src="/images/image_2.jpg" alt="1904380_VANI"></div>
<div><img src="/images/image_3.jpg" alt="1904380_WHIT"></div>
<div><img src="/images/image_4.jpg" alt="1904381_BERR"></div>
</main>

$(document).ready(function() {

var list = ("1904381_BERR", "1904380_ORAN");                        
$('img').each(function(){
    if($(this).attr("alt") == list ){             
          $(this).before("<img src=/images/guide/dropped.png class=cxl>");
          }
      });
});

Upvotes: 0

Views: 118

Answers (2)

VVV
VVV

Reputation: 7593

Here is a working fiddle

$(document).ready(function() {

  var list = ["1904381_BERR", "1904380_ORAN"];
  $('img').each(function(_i, _e) {
    if (jQuery.inArray($(this).attr('alt'), list) > -1) {
      $(this).before('<img src="/images/guide/dropped.png" class="cxl">');
    }
  });
});

There was some problems with your code.

  • The list variable was not an array
  • The way you compared the list to an array was incorrect.
  • The <img> tag you include before needs more quotes to separate the attributes.

Upvotes: 1

vladimir
vladimir

Reputation: 15226

As mentioned in comment need to use an array and just check that alt contains required value:

$(document).ready(function() {

    var list = ["1904381_BERR", "1904380_ORAN"];

    $('img').each(function() {
        if (list.indexOf($(this).attr("alt")) !== -1) {
            $(this).before('<img src="/images/guide/dropped.png" class="cxl">');
        }
    });
});

Upvotes: 0

Related Questions