Filter jQuery object using plugin
I am trying to create a jQuery plugin that filters the provided jQuery object to only return some elements similar to the .filter (expr) function. This is more for education and then for real trouble. However, I cannot figure out how to remove the elements from the provided jQuery object (or only return some others, it doesn't matter).
Example code (Yes, I know you can do this with a filter (': Nth-child (n)'), but as I said, this is for self-learning):
$.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 to do it?
EDIT
I am really looking for a way to remove certain elements from a jQuery object, not some clever way to solve the above problem. So I don't want to return a subset of the provided jQuery object.
a source to share
I think you would like to use the filter (fn) function for which you can provide a function to be called on every element in the jQuery object. If the function returns false, the item is removed.
For example, this will filter out the 5th element and the element with id 'blue':
$("div").filter(function (index){
return !(index == 5 || this.id == "blue");
});
Alternatively, you can implement your own custom selector and use the filter function (expr) you talked about.
a source to share