Reputation: 175
I need to check if any <li>
's has an ID which is matching any of the ID's given from the string 1001,1002,1003,
outputted by arrayList
in the for()
loop.
var wishArray = $.parseJSON($.cookie('wishlist_cookie'));
var arrayList = '';
var li = $('ul li');
var str = li.attr('id');
for (i = 0; i < wishArray['itemlist'].length; i++) {
arrayList += wishArray['itemlist'][i].wishlist_item_id + ",";
console.log(arrayList);
}
Then addClass to ALL <li>
where ID is equal to any of 1001,1002,1003,
if (arrayList.indexOf(str) != -1) {
if($('ul li').attr('id', idvalue)){
$(this).addClass('found');
}
}
How can I make it check all <li>
ID's and then apply .addClass('found')
to all <li>
which matches the IDs outputted by arrayList
?
Upvotes: 0
Views: 173
Reputation: 171669
All you really need to do is create a selector from the array.
$('#' + wishArray['itemlist'].join(', #') ).addClass('found');
// would create
//$('#0001, #0002, #003').addClass('found');
Upvotes: 0
Reputation: 43718
Why not simply something like this instead?
Here we construct a jQuery CSS selector that will match every li with one of the listed id and let jQuery do the rest.
var lisSelector = wishArray['itemlist'].map(function (item) {
return 'li[id="' + item.wishlist_item_id + '"]';
}).join(',');
$(lisSelector).addClass('found');
Note that if you do not care wheter the element is an <li>
or not, you can simply generate a selector with '#' + item.wishlist_item_id
.
Upvotes: 1
Reputation: 85545
variable li already contain id and using again in variable str, you may remove that:
var li = $('ul li')//.attr('id');
var str = li.attr('id');
Upvotes: 1