views:

428

answers:

3

I'm somewhat new to jQuery/javascript, and would like to compare the contents of row[i] in a table body with row[i+1].

Is this something I can do with jQuery or should I just use plain old JS and getElementByid and then loop that way? using the .each doesn't appear to give anyway of accessing the next element in the series easily.

I assume if/when I find a solution to this, I then need to figure out how to compare row[i].td[j] to row[i+1].td[j].

I imagine this is simple, but my searches so far have come up with null.

+4  A: 

note that next may end up being an empty jquery object if you're at the last tr

var trs = $('tr');
trs.each(function(i,n) {
    var current = $(n);
    var next = trs.eq(i+1);
});
David Hedlund
A: 

You could store the previous element and do the compare on the 'next':

  var callback = (function() {
   var lastTr;

   return (function(i, n) {
       if (lastTr) {
           //logic $(this) is 'next', lastTr is 'current'
       }

       lastTr = $(this);
   });
  })();;

  $(document).ready(function() {
   $('tr').each(callback); 
  });
BranTheMan
A: 

my full solution so far involves something along these lines:

  function myfunc(table) {
    $(table).each(function(i,n) {
      var current = $(n);
      var next = $(table).eq(i+1);
      if (next.length) {
        current.children().each(function(a,b) {
          var current_td = $.trim($(b).text());
          var next_td = $.trim(next.children().eq(a).text());
          /* compare here */
        });
      }
    });
  }
lostincode