Pruebe esto. Marcará su elemento, creará un conjunto de elementos que coincidan con su selector y recogerá todos los elementos del conjunto que sigue a su elemento.
$.fn.findNext = function (selector) {
var set = $([]), found = false;
$(this).attr("findNext" , "true");
$(selector).each(function(i , element) {
element = $(element);
if (found == true) set = set.add(element)
if (element.attr("findNext") == "true") found = true;
})
$(this).removeAttr("findNext")
return set
}
EDITAR
mucho más simple solución utilizando jquerys método de índice. el elemento se llama al método de las necesidades para ser seleccionable por el mismo selector aunque
$.fn.findNext = function(selector){
var set = $(selector);
return set.eq(set.index(this,) + 1)
}
para liberar la función de esta desventaja, podríamos youse los navegadores poseen compareDocumentposition
$.fn.findNext = function (selector) {
// if the stack is empty, return the first found element
if (this.length < 1) return $(s).first();
var found,
that = this.get(0);
$(selector)
.each(function() {
var pos = that.compareDocumentPosition(this);
if (pos === 4 || pos === 12 || pos === 20){
// pos === 2 || 10 || 18 for previous elements
found = element;
return false;
}
})
// using pushStack, one can now go back to the previous elements like this
// $("#someid").findNext("div").remove().end().attr("id")
// will now return "someid"
return this.pushStack([ found ]);
},
EDIT 2 esto es mucho más fácil usando $ .grep de jQuery. aquí está el nuevo código
$.fn.findNextAll = function(selector){
var that = this[ 0 ],
selection = $(selector).get();
return this.pushStack(
// if there are no elements in the original selection return everything
!that && selection ||
$.grep(selection, function(n){
return [4,12,20].indexOf(that.compareDocumentPosition(n)) > -1
// if you are looking for previous elements it should be [2,10,18]
})
);
}
$.fn.findNext = function(selector){
return this.pushStack(this.findNextAll(selector).first());
}
al comprimir los nombres de las variables, esto se convierte en un simple dos delineador.
Editar 3 usando operaciones bit a bit, ¿esta función puede ser aún más rápida?
$.fn.findNextAll = function(selector){
var that = this[ 0 ],
selection = $(selector).get();
return this.pushStack(
!that && selection || $.grep(selection, function(n){
return that.compareDocumentPosition(n) & (1<<2);
// if you are looking for previous elements it should be & (1<<1);
})
);
}
$.fn.findNext = function(selector){
return this.pushStack(this.findNextAll(selector).first());
}
posible duplicado de [jQuery para encontrar todos los elementos anteriores que coincidan con una expresión] (http://stackoverflow.com/questions/322912/jquery-to-find-all-previous-elements-that-match- an-expression) – sachleen