Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the 'n' number of first or last elements with jQuery in an optimal way?

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.

like image 279
Kees C. Bakker Avatar asked Feb 25 '12 10:02

Kees C. Bakker


People also ask

How to remove an element using jQuery?

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.

How to remove n elements from end of array JavaScript?

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.

How to remove element inside div using jQuery?

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.


1 Answers

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.

like image 89
dfsq Avatar answered Oct 29 '22 16:10

dfsq