Reputation: 2937
I was quite sure that I already did this in some earlier version of jQuery, but http://api.jquery.com/category/traversing/ seems to suggest otherwise.
What I'm looking for is similar kind of the opposite of .addBack()
- a traversing function that uses "all other" elements (not .not()
!)
Preusdo Example:
$('.some-class li').slice(33,55).hide().allOthers().show()
Edit: This is not actually a hide() / show() based problem, this is just a simple example to clarify what I meant.
First, I'ld like to manipulate a set of elements selected with .slice()
, and then manipulate all elements that were not selected by .slice()
.
Is there a handy traversing function I've missed that does just that? I know how to solve it in general, but a ".allOthers()"
method that I might have missed would certainly be more handy and clearer.
Upvotes: 2
Views: 67
Reputation: 92274
In your case you can just call show before calling slice
$('.some-class li').show().slice(33,55).hide();
It's true that there is no method to get all others, the closest is to get back they previous collection as you mentioned, http://api.jquery.com/addback/
You could implement a plugin, since I'm on my mobile, I'll just write some straight code
// o(n*m), could be improved
function allOthers(jqObj) {
var current = [].concat(jqObj);
var prev = jqObj.addBack();
return prev.filter(function(obj){
return !current.includes(obj);
});
}
Upvotes: 2
Reputation: 2937
After testing @JuanMendes suggestion, I played around with it a bit and found quite a compact way to implement this kind of functionality, due to jQuery's prevObject:
$.fn.others = function() {
return this.prevObject.not( this );
}
I didn't test it too much with other methods, so it might needs some further changes - but it seems to work fine with .slice()
at least.
https://jsfiddle.net/1L3db7k4/
Upvotes: 1
Reputation: 68393
First show all of them and then hide from 33 to 55, here is the demo
$('.some-class li').show().slice(33,55).hide();
Upvotes: 1