ButsAndCats ButsAndCats - 1 month ago 9
jQuery Question

jQuery - Passing a variable into .not() within a foreach loop

When I use the following code without a variable it works fine:

$( "div#bottomSelector div button" ).not( "#black" ).addClass('greyed');


However when to replace the id's with a variable and loop for each one it doesn't. It applies the
greyed
class to all of the buttons within the selector.

variants.split(",").forEach(function(each) {
var id = '#' + each
console.log ( id );
$( "div#bottomSelector div button" ).not( id ).addClass('greyed');
});


The console log for this returns the following:

#bamboo
#black
#white


The markup is:

<div id="bottomSelector">
<div><button id="bamboo">Bamboo</button></div>
<div><button id="black">Black</button></div>
<div><button id="walnut">Walnut</button></div>
<div><button id="gold">Gold</button></div>
<div><button id="white">White</button></div>
</div>

Answer

In each iteration of your loop, 2/3 of your buttons qualify for getting the greyed class.

This is because #black and #white match not('#bamboo'). Next time around, #bamboo matches not('#black') and all three of your buttons now have the greyed class added.

What you should do instead is make sure that each element has NONE of the ID's. You can do this pretty easily by just chaining calls to $().not

This is due to a logical equivalence that can be a little bit unintitive if you don't write it out.

!A || !B || !C === !(A && B && C)

When what you want is

!A && !B && !C === !(A || B || C)

The code you want is something more like this:

var buttons = $( "div#bottomSelector div button" );
variants.split(",").forEach(function(each) {
  var id = '#' + each
  buttons = $(buttons).not( id );
});
$(buttons).addClass('greyed');