Reputation: 986
I have an array of products that I want to be able to check via jQuery to see if any of them are present in a images source url. I've made the following but dont know the correct way to call my variable inside the script:
$(function() {
/*Products we to target*/
var products = ["product1.jpg", "product2.jpg", "product3.jpg"];
$('ul.product-list li img[src*=products]').addClass('targeted-product');
});
How do I call my variable inside the img[src*=]
selector and is the above code is going to work?
Upvotes: 0
Views: 133
Reputation: 12544
To add one more to the mix, using filter:
$('ul.product-list li img').filter(function(){return products.indexOf($(this).attr('src')) !== -1;}).addClass('targeted-product');
Upvotes: 0
Reputation: 133403
You can create a valid selector using the array, then use .find()
to get the descendants.
var selector = products.map(function (p) {
return "img[src*=" + p + "]"
}).join(',');
//Use the selector string
$('ul.product-list li').find(selector).addClass('targeted-product');
Upvotes: 1
Reputation: 666
Try this:
$(function() {
/*Products we to target*/
var products = ["product1.jpg", "product2.jpg", "product3.jpg"];
$.each( products, function( key, value ) {
$('ul.product-list li img[src^="' + value + '"]').addClass('targeted-product');
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<style>
.targeted-product{background-color: green;}
</style>
<body>
<ul class="product-list">
<li><img src ="product1.jpg"/></li>
<li><img src ="product2.jpg"/></li>
<li><img src ="product4.jpg"/></li>
<li><img src ="product5.jpg"/></li>
<li><img src ="product3.jpg"/></li>
</ul>
</body>
</html>
Upvotes: 1
Reputation: 366
Try this code
$(function() {
/*Products we to target*/
var products = ["product1.jpg", "product2.jpg", "product3.jpg"];
for(i=0; i<products.length; i++) {
$('ul.product-list li img[src*=]'+products[i]).addClass('targeted-product');
}
});
Upvotes: 1
Reputation: 593
Try with following:
Just need to add:
$('ul.product-list li
img[src*='+products['0']+']').addClass('targeted-product');
$(function() {
/*Products we to target*/
var products = ["product1.jpg", "product2.jpg", "product3.jpg"];
$('ul.product-list li img[src*='+products['0']+']').addClass('targeted-product');
});
Upvotes: 0