You can use this:
$("#sourceT tr").each(function(index) {
var newRow = $("<tr></tr>");
$(this).find("td:lt(2)").each(function() {
newRow.append($(this).clone());
})
$("#targetT").append(newRow);
});
Working demo: http://jsfiddle.net/jfriend00/JRwVN/
Or an even more compact version that uses more chaining instead of the .each()
:
$("#sourceT tr").each(function(index) {
var newRow = $("<tr></tr>");
$(this).find("td:lt(2)").clone().appendTo(newRow);
$("#targetT").append(newRow);
});
Demo: http://jsfiddle.net/jfriend00/QRVfE/
Any code, regardless of selectors, that finds the columns you want is going to look in every row of the table. Walking the DOM (which is what these selector operations do) is not a slow operation. What is a slow operation is creating new DOM objects and inserting them in the DOM and there's no way to avoid that in your case.
If performance was super critical (something you should prove is actually a problem before attacking it), there are actually times when it's faster to create a giant HTML string and put that into the DOM all at once rather than inserting individual DOM objects.
If performance was critical, a version that constructs an HTML string seems to be about 20% faster in Chrome, IE10 and Firefox. It works like this:
var newTable = "";
$("#sourceT tr").each(function(index) {
newTable += "<tr>";
$(this).find("td:lt(2)").each(function() {
newTable += "<td>" + this.innerHTML + "</td>";
});
newTable += "</tr>";
});
$("#targetT").html(newTable);
Demo: http://jsfiddle.net/jfriend00/MDAKe/
And, the jsperf that compares the last two ways: http://jsperf.com/table-copy
I'm sure there are other ways to improve performance (usually jQuery itself doesn't give you the fastest running code).
As it turns out, removing all jQuery makes it about 8-12x faster (depending upon browser):
var newTable = "";
var rows = document.getElementById("sourceT").rows;
for (var i = 0, len = rows.length; i < len; i++) {
var cells = rows[i].cells;
newTable += "<tr><td>" + cells[0].innerHTML + "</td><td>" + cells[1].innerHTML + "</td></tr>";
}
document.getElementById("targetT").innerHTML = newTable;
Demo: http://jsfiddle.net/jfriend00/7AJk2/