Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Filter and Reverse Filter

Tags:

jquery

I'm looking for a shorter way of writing:

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

Hopefully something along the lines of:

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

I'd like to define 'runMyTestFunction' inline as a lambda since I think it will make the code clearer but as written I would have to duplicate it.

like image 269
Mike Edwards Avatar asked Jun 04 '11 17:06

Mike Edwards


1 Answers

You could do:

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

If you don't want to run the 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();
like image 66
Felix Kling Avatar answered Sep 21 '22 01:09

Felix Kling