In jQuery, filter()
reduces your result to those elements that fulfill a certain condition.
This splits the list in two parts. Working with the "good half" of the elements is easy:
$("some selector").filter(function() {
// determine result...
return result;
}).each( /* do something */ );
But how can I work with the "other half" of my elements, too - but without doing the equivalent of this:
$("some selector").filter(function() {
// determine result...
return !result;
}).each( /* do something else */ );
Basically, I'd like to feed two separate /* do something */
parts to a single filter. One for those that match, and one for the others - without having to filter twice. Am I missing a jQuery function that does this?
P.S.: I guess I could do:
$("some selector").each(function() {
// determine result...
if (result)
/* do something */
else
/* do something else */
});
But I was hoping for something nicer.
The filter() method does not change the original array.
jQuery not() Method The not() method returns all elements that do not match the criteria. Tip: The not() method is the opposite of filter() .
jQuery selector selects all elements based on the elements name given by you. jQuery filter( ) adds further detail to the selected elements by specifying the criteria of selection.
JQuery provides several methods that you can use to narrow down the search for elements in a DOM tree for example filter ( ), first ( ), last ( ), eg ( ), slice ( ), has ( ), not ( ), etc. The above all are filtering methods of jQuery.
The method recommended by Kobi in plugin form:
$.fn.invert = function() {
return this.end().not(this);
};
$('.foo').filter(':visible').hide().invert().show();
Note that invert()
will not add a new element to the jQuery stack but replace the last one:
$('.foo').filter(':visible').invert().end(); // this will yield $('.foo'), not $('.foo:visible')
Edit: changed prevObject
to end()
at Tomalak's suggestion.
I usually use not
for this - it can take an array of elements and remove them from your selection, leaving you with the complement:
var all = $("some selector");
var filtered = all.filter(function() {
// determine result...
return result;
});
var others = all.not(filtered);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With