Reputation: 3
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
Reputation: 7593
$(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.
<img>
tag you include before
needs more quotes to separate the attributes.Upvotes: 1
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