JQuery filter and inverse filter

I am looking for a shorter way to write:

$('div')
.filter(function(value) {
   return runMyTestFunction(value);
})
.hide()
.end()
.filter(function(value) {
   return !runMyTestFunction(value);
})
.show();

Hope something like:

$('div')
.filter(function(value) {
   return runMyTestFunction(value);
})
.hide()
.end()
.remove(theLastWrappedSetPoppedOfftheJqueryStack)
.show();

I want to define the "runMyTestFunction" inline as lambda, since I think this will make the code more clear, but as it is written, I will have to duplicate it.

+5
source share
1 answer

You can do:

$('div')
.filter(runMyTestFunction);
.hide()
.end()
.not(runMyTestFunction)
.show();

If you do not want to run this method twice:

$('div')
.hide() // hide all
.not(runMyTestFunction)
.show();

Or, if you explicitly want to hide only certain elements:

var elements = $('div');
var toRemove = elements.filter(runMyTestFunction).hide();
elements.not(toRemove).show();
+9
source

All Articles