Tommy Pradana Tommy Pradana - 5 months ago 9
jQuery Question

How to add a class to an element which has a class name not in array

I'm trying to add a "disabled" class to an element which has a class name not in array, and I have an array output like this :

["xs", "xl", "s", "m"]


and the html markup like this:

<a href="js:;" class="pa_size xs" title="xs" data-select="pa_size" data-value="xs">XS</a>
<a href="js:;" class="pa_size xl" title="xl" data-select="pa_size" data-value="xl">XL</a>
<a href="js:;" class="pa_size s" title="s" data-select="pa_size" data-value="s">S</a>
<a href="js:;" class="pa_size m" title="m" data-select="pa_size" data-value="m">M</a>
<a href="js:;" class="pa_size l" title="l" data-select="pa_size" data-value="l">L</a>


I have tried something like this:

if ( $.inArray(val, array) !== -1 ) { ... }


or

$.each(array, function() { ... }


but no luck.

Answer

Generate multiple class selector using the array and avoid them using :not() pseudo-class or not() method in jQuery.

var classes = ["xs", "xl", "s", "m"];

$('a').not(classes.map(function(v) {
  // iterate and add `.` before each element
  return '.' + v; 
  // join using `,` to act them as multi selector
}).join(',')).addClass('class')
.class {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="js:;" class="pa_size xs" title="xs" data-select="pa_size" data-value="xs">XS</a>
<a href="js:;" class="pa_size xl" title="xl" data-select="pa_size" data-value="xl">XL</a>
<a href="js:;" class="pa_size s" title="s" data-select="pa_size" data-value="s">S</a>
<a href="js:;" class="pa_size m" title="m" data-select="pa_size" data-value="m">M</a>
<a href="js:;" class="pa_size l" title="l" data-select="pa_size" data-value="l">L</a>


Or even more simpler as @charlietfl suggested

var classes = ["xs", "xl", "s", "m"];

$('a').not('.' + classes.join(',.')).addClass('class')
.class {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="js:;" class="pa_size xs" title="xs" data-select="pa_size" data-value="xs">XS</a>
<a href="js:;" class="pa_size xl" title="xl" data-select="pa_size" data-value="xl">XL</a>
<a href="js:;" class="pa_size s" title="s" data-select="pa_size" data-value="s">S</a>
<a href="js:;" class="pa_size m" title="m" data-select="pa_size" data-value="m">M</a>
<a href="js:;" class="pa_size l" title="l" data-select="pa_size" data-value="l">L</a>