views:

133

answers:

3

Can anyone please help me to work out how to achieve the following? I have a set of divs of unknown size. Each div has a class of .feature. I need to run a jQuery script to find all divs with .feature and then find all children as a series of pairs. Each pair will then be submitted to a further jQuery function.

For example:

1. <div.feature/>
2. <div.feature/>
3. <div.feature/>
4. <div.feature/>
5. <div.feature/>

The result should be that 1+2 and 3+4 get paired together such that I can then call another jQuery function on each of these individual sets.

I know that I can simply wrap each pair in an outer div and then find each wrapper divs children but I'd like to avoid changing the markup if possible.

Thanks in advance.

+2  A: 
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');
Pointy
Hey thanks, I can't test right now but that looks about right.
Brian Scott
Pointy
This looks strange, $() equals $(document)
David
@David that was true up until jQuery version 1.4
Pointy
Isn't this somewhat complicated?
Adam Kiss
@Pointy: Thanks! I missed that, and it makes a lot more sense.
David
@Adam well complexity is in the eye of the beholder :-) When I first wrote it, making believe it was C, I didn't need the temp. variable. If there were a jQuery "zip" builtin, you could zip together the :even and :odd divs to make the pairs array, and that'd be simpler.
Pointy
+1  A: 

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

Adam Kiss
A: 

Let's jump to the assumption that you can fix the HTML to make it valid, and it looks like:

<div class='feature'></div>
<div class='feature'></div>
<div class='feature'></div>
<div class='feature'></div>
<div class='feature'></div>
<div class='feature'></div>

You can then use a selector like:

$("div:odd")

or

$("div:even")

more like:

$("div:even").children(':even');

NOTE: 0 based index, so 2,4,etc (normal count) are ODD...

Mark Schultheiss