ButsAndCats ButsAndCats - 1 year ago 72
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
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:


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>

Answer Source

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 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download