I have a table with many rows (+50) and cells (+50). Now I would like to remove the n first or last cells with jQuery. Currently I have the following code:
var n = 10;
var last = true;
for (var i = 0; i < n; i++) {
table.find('tr').each(function() {
if(last)
$(this).find('td:last').remove();
else
$(this).find('td:first').remove();
});
}
Note: table
is a jQuery element.
The code works, but performs very slow when I have a table with 50 rows with 50 cells and I remove the 10 last cells. Any ideas how to optimize the code?
Edit: I've added the first clause as well.
To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.
The pop() method in JavaScript is used to remove the last element from the array. This can be repeated in a loop of n iterations to remove the last n elements of the array using the while loop.
version added: 1.0. remove() method takes elements out of the DOM. Use . remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
The optimal I think could be using nth-last-child
.
table.find("tr td:nth-last-child(-n+10)").remove();
Benefit is that internal browser CSS selector engine will be used (or in case of IE jQuery will help a little :) Here is the demo removing last 3 elements. Change it to 10 in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With