Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: use filter(), but work with both results

Tags:

jquery

filter

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.

like image 795
Tomalak Avatar asked May 09 '10 17:05

Tomalak


People also ask

Does. filter return a new array?

The filter() method does not change the original array.

Which jQuery method does the opposite of filter method?

jQuery not() Method The not() method returns all elements that do not match the criteria. Tip: The not() method is the opposite of filter() .

What is the main difference between selectors and filters in jQuery?

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.

What are the jQuery most basic filtering methods?

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.


2 Answers

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.

like image 188
Tgr Avatar answered Sep 17 '22 01:09

Tgr


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);
like image 43
Kobi Avatar answered Sep 18 '22 01:09

Kobi