Reputation: 237865
With most jQuery function calls that change the selection, it is possible to go back a step in the selection using end
. For example:
$('#myElement').parent().show().end().css('color', '#ff0000');
This shows the parent element and then makes the original selection red.
However, when I define my own jQuery plugin that filters a selection, I don't get this functionality. For example:
$.fn.nextBarOne = function(selector) {
var ret = this.next().next();
return (typeof selector === 'undefined') ? ret : ret.filter(selector);
}
If I now do $('#myElement').nextBarOne().show().end()
I don't go back to the original selection. Obviously this is because internally the function calls next
twice and then sometimes calls filter
.
How can I define a jQuery plugin to allow me to use end
like the built-in functions do?
Upvotes: 4
Views: 213
Reputation: 125488
Set prevObject
after traversing using .next()
to point to the original jQuery object.
$.fn.nextBarOne = function(selector) {
var self = this,
ret = (typeof selector === 'undefined') ?
this.next().next() : this.next().next().filter(selector);
ret.prevObject = self;
return ret;
}
EDIT:
Possibly cleaner with pushStack()
. I've also included the selector in the pushStack
call.
$.fn.nextBarOne = function(selector) {
var ret = (typeof selector === 'undefined') ?
this.next().next() : this.next().next().filter(selector);
return this.pushStack(ret, "nextBarOne", selector || "");
}
Upvotes: 3