Reputation: 583
I am trying to target the actual element mentioned in my conditional statement, here is an example of my code:
let selectValue = $('.Select input').val();
if ($('.vehicle-item').attr('data-value') != selectValue) {
//Add a class to the element that hasn't got an attribute equal to the `selectValue` variable.
}
So basically on my page there are multiple elements with the class of .vehicle-item
some of these will pass the conditional statement and some wont. I would like to add a class to all of the elements with that class that don't pass the conditional statement.
If I could somehow iterate over that conditional statement for every element that didn't pass and add a class that would work however how do I do this?
Upvotes: 3
Views: 192
Reputation: 337570
You can use filter()
to achieve this:
let selectValue = $('.Select input').val();
$('.vehicle-item').filter(function() {
return $(this).data('value') != selectValue;
}).addClass('foo');
Alternatively you could use the attribute selector:
let selectValue = $('.Select input').val();
$('.vehicle-item[data-value!="' + selectValue + '"]').addClass('foo');
Note that the latter reads the data attribute directly from the element, so if you update the value programmatically after the page has loaded you will have to use filter()
.
Personally I would use filter()
anyway as it's slightly faster in most browsers and I find it easier to read.
Upvotes: 2
Reputation: 1493
You can do that directly using "not equal" selector and multiple selector feature.
$(".vehicle-item[data-value!='"+selectValue+"']").each(function(){
// do something
});
Upvotes: 0