Source : jQuery find next/prev elements of a certain class but not necessarily siblings (EDIT 3).
Les méthodes next
, prev
, nextAll
et prevAll
sont très utiles pour parcourir le DOM à la recherche d’un ou plusieurs éléments frères d’un élément situé dans le même parent. Mais comment procéder si l’élément suivant ou précédent qu’on cherche à cibler se situe à l’extérieur de l’élément parent propre à notre élément de départ ?
Dans l’exemple suivant, je cherche à atteindre la classe .to-find-this
en partant de l’ID #start-from-here
.
1 2 |
<div><span id="start-from-here">hello</span></div> <div><p class="to-find-this">world></p></div> |
Cette action est rendue possible grâce aux fonctions jQuery suivantes :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$.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() ); } |
Je peux désormais cibler la classe .to-find-this
en partant de l’ID #start-from-here
avec la déclaration suivante :
1 |
$('#start-from-here').findNext('.to-find-this'); |