noclist noclist - 3 months ago 36
Javascript Question

nested loop with jQuery eq()

I have the following loop:

for (i = 0; i < Count; i++) {

$('td').eq(i).prepend($('th').eq(???).text() + '<br />');
}


I will always want the
td
element at index
i
, however I only want to prepend the
th
element that is at index 0, 1, or 2.

Example:

prepend th 0 to td 0

prepend th 1 to td 1

prepend th 2 to td 2

prepend th 0 to td 3

prepend th 1 to td 4

prepend th 2 to td 5

How can I perform this loop inside of my eq()? Is eq() the correct method to accomplish this? Thanks.

Answer

Simply iterate over th using each() method then get all corresponding td using the index with help of :nth-child() and prepend the content.

// iterate over th
$('th').each(function(i){
  // get td elements in same column using index
  $('td:nth-child(' + (i + 1) + ')').prepend($(this).text() + '<br/>');
});

With your own for loop generate the index by taking modulus and update.

// cache the th and td
var $th = $('th'),
      $td=$('td'),
      // store counts of th
      c = $th.length;

// iterate over th
for (i = 0; i < Count; i++) {
   // update wuth corresponding th text
   // where `i % c` refers to the index
   $td.eq(i).prepend($th.eq(i % c).text() + '<br />');
}

Or much simpler way with for loop(same logic as in the first method).

var $th = $('th'),
      c = $th.length;

for (i = 1; i <= c; i++) {
   $('td:nth-child(' + i + ')').prepend($th.eq(i).text() + '<br />');
}
Comments