user519477
user519477

Reputation:

How to write jQuery traversal function

I want to write a jQuery function called nextOrPrev() that works similar to jQuery's next() and prev(), which returns the next sibling or, in case there isn't any, the previous one. The function should be compatible with jQuery's existing traversal functions like siblings(), but also end().

What do I have to write in $.fn.extend()?

My attempt was to create an array and then populate it in a this.each loop and at the end, return it, but returning that creates a new stack.

Upvotes: 0

Views: 38

Answers (1)

adeneo
adeneo

Reputation: 318342

Shouldn't be a problem, just write it like any jQuery plugin

$.fn.nextOrPrev = function() {
    var args = arguments;
    return $(this).map(function(_,el) {
        var next = $.fn.next.apply($(el), args);
        return (next.length ? next : $.fn.prev.apply($(el), args)).get();
    });
}

and use it

$('#elem1, #elem2').nextOrPrev()

FIDDLE

Upvotes: 1

Related Questions