Question

for (var i = 0; i <= $('#table-body tr').length - 1; i++) {
    var ingredients = $('#recipiestable tbody tr:nth-child(2) td:nth-child(1)').text()
    var amount = $('#recipiestable tbody tr:nth-child(2) td:nth-child(2)').text()
    var unit = $('#recipiestable tbody tr:nth-child(2) td:nth-child(3)').text()
    $('#resultsbody').append('<tr><td>' + ingredients + '</td><td>' + amount + '</td><td>' + unit + '</td> </tr>')
}

How can I select the nth-child using i in the loop? I've tried:

$('#recipiestable tbody tr:nth-child('+ i +') td:nth-child(1)')

But it just returns errors, does anyone know how to work around this?

Was it helpful?

Solution

How about a little refactoring to better understand your code?

var table_size = $('#table-body tr').length;
var trs = $('#recipiestable tbody tr').slice(table_size);

$.each(trs, function(i, tr) {
  // No need for messy lookups, if you can look inside the context of your current tr
  var ingredients = $('td:nth-child(1)', tr).text(),
      amount      = $('td:nth-child(2)', tr).text(),
      unit        = $('td:nth-child(3)', tr).text();

  $('#resultsbody').append('<tr><td>' + ingredients + '</td><td>' + amount + '</td><td>' + unit + '</td> </tr>');
});

docs for $.each

OTHER TIPS

for (var i = 0; i <= $('#table-body tr').length - 1; i++) {
    var ingredients = $('#recipiestable tbody tr:nth-child(2) td:nth-child(1)').text();
    var amount = $('#recipiestable tbody tr:nth-child(2) td:nth-child(2)').text();
    var unit = $('#recipiestable tbody tr:nth-child(2) td:nth-child(3)').text();
    $('#resultsbody').append('<tr><td>' + ingredients + '</td><td>' + amount + '</td><td>' + unit + '</td> </tr>');
}

Please add the semicolons ;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top