How do I select every pair of 2 sequential elements in jQuery?

var pairs = [];
$('div.feature').each(function(i, div) {
  var i_over_2 = Math.floor(i / 2);
  if (!pairs[i_over_2]) pairs[i_over_2] = $();
  pairs[i_over_2] = pairs[i_over_2].add(div);
});
$.each(pairs, function(i, p) {
  p.doSomethingToAPair();
});

The idea is to build up an array of jQuery objects.

edit looks like 1.4 added "$()" to get an empty jQuery object.

edit again durr Javascript has floats :-)

Hey @Adam: if we had this jQuery extension (this is a toy version of course):

jQuery.fn.zip = function(s) {
  var o = $(s);
  return this.map(function(i, e) {
    return $(e).add($(o[i]));
  });
};

then we could build the "pairs" array like this:

var pairs = $('div.feature:even').zip('div.feature:odd');

idea

$('div.feature:even').each(function(){
  var t = $(this);
  var paired = t.add( $('div.feature:eq('+(t.index()+1)+')', t.parent()) );
  //add to array, call function...
}

May need little tweaking in order to work for you - it's untested.

preview

http://jsbin.com/okize/7

Tags:

Jquery