views:

180

answers:

2

I'm trying to build a jQuery plugin that filters the provided jQuery object to only return some elements similar to the .filter(expr) function. This is more for educationg myself then for a real world problem. However I can't figure out how to remove elements from the provided jQuery object (or only return certain others, doesn't really matter).

Code sample (Yes I know you can do this using filter(':Nth-child(n)') but as I said this is for educating myself):

$.fn.notNthElement = function(n){
    var i=0;
    this.each( function(){
        i++;
        if(i==n){
            //remove element from this jQuery object (not from DOM)
            i=0;
        }
        //or alternatively:
        else{
            //push this to some result jQuery object
        }
    });
    return this; //or when going the alternative route, return the result jQuery object
}

How would one do this?

EDIT
I'm really looking for a way to remove specific elements from the jQuery object, not some clever way to solve the above problem. So I wan't to return a subset of the provided jQuery object.

A: 

Note: Have not tried this, but think it works. See it as meta-code... (though it might work just as is.)

$.fn.notNthElement = function(n){
  var $this = $(this);
  return $this.slice(0,n-1).add($this.slice(n));
};
svinto
+1  A: 

I think you would want to use the filter (fn) function, to which you can supply a function that is called for each item in the jQuery object. If the function returns false the item is removed.

For instance, this would filter out the 5th item and the item with id 'blue':

$("div").filter(function (index){
    return !(index == 5 || this.id == "blue");
});

Alternatively, you could implement your own custom selector, and use the filter(expr) function that you referred to.

Mario Menger
Thnx, I never noticed the .filter method took a function as argument.
Pim Jager