Nick Maddren Nick Maddren - 1 year ago 68
jQuery Question

Target individual element mentioned in conditional statement jQuery

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
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?

Answer Source

You can use filter() to achieve this:

let selectValue = $('.Select input').val();
$('.vehicle-item').filter(function() {
    return $(this).data('value') != selectValue;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download