code_junkie

How to select consecutive elements that match a filter

Nov 10th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. <img class="a" />
  2. <img />
  3. <img class="a" />
  4. <img class="a" id="active" />
  5. <img class="a" />
  6. <img class="a" />
  7. <img />
  8. <img class="a" />
  9.  
  10. // here's our active element.
  11. var $active = $('#active');
  12.  
  13. // here is the filter we'll be testing against.
  14. var filter = "img.a";
  15.  
  16. // $all will be the final jQuery object with all the consecutively matched elements.
  17. // start it out by populating it with the current object.
  18. var $all = $active;
  19.  
  20. for ($curr = $active.prev(filter); $curr.length > 0; $curr = $curr.prev(filter)) {
  21. $all = $all.add($curr);
  22. }
  23. for ($curr = $td.next(filter); $curr.length > 0; $curr = $curr.next(filter)) {
  24. $all = $all.add($curr);
  25. }
  26.  
  27. $('#active')
  28. .nextAll()
  29. .each(hideConsecutive)
  30. .end()
  31. .prevAll()
  32. .each(hideConsecutive)
  33. ;
  34. function hideConsecutive(index, element) {
  35. var $e = $(element);
  36. if (!$e.is(".a")) {
  37. return false; // this stops the each function.
  38. } else {
  39. $e.hide('slow');
  40. }
  41. }
  42.  
  43. var $all =
  44. (name == 'prev')
  45. ? $(this).prevAll()
  46. : $(this).nextAll();
  47. if (!matchExpr)
  48. return $all;
  49.  
  50. var $notMatch = $($all).not(matchExpr).filter(':first');
  51. if ($all.index($notMatch) != -1)
  52. return $allConsecutive = $all.slice(0, $all.index($notMatch));
  53.  
  54. return $all;
  55. };
  56.  
  57. $('#active ~ img.a').hide();
  58.  
  59. $('#active ~ img.a')
  60.  
  61. var next = $('#active').next('.a');
  62. var prev = $('#active').prev('.a');
Add Comment
Please, Sign In to add comment