Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty rows and columns in a table with jQuery

Suppose I have a table like this:

+-----------+
| | | | | | |
|-+-+-+-+-+-|
| |a| |b| | |
|-+-+-+-+-+-|
| | | | | | |
|-+-+-+-+-+-|
| |c| |d| | |
|-+-+-+-+-+-|
| | | | | | |
+-----------+

I want to remove all of the outside rows and columns that are empty. The above example will be reduced to this:

+-----+
|a| |b|
|-+-+-|
| | | |
|-+-+-|
|c| |d|
+-----+

I have some working code, but it is not very elegant and, more importantly, prohibitively slow. I need a solution that can remove up to 30 extraneous rows and columns quickly.

Is there a fast and halfway-decent way to do this?

like image 889
Peter Olson Avatar asked Jan 19 '23 00:01

Peter Olson


1 Answers

var $theTable = $("table#myTable"),
    lookAt    = ["tr:first-child", "tr:last-child", 
                 "td:first-child", "td:last-child"];

for (var i=0; i<lookAt.length; i++) {
  while ( $.trim($(lookAt[i], $theTable).text()) == "" ) {
    $(lookAt[i], $theTable).remove();
  }
}

EDIT: You could use this as the inner loop, maybe it's a little faster:

for (var i=0; i<lookAt.length; i++) {
  while ( var $x = $(lookAt[i], $theTable), $.trim($x.text()) == "" ) {
    $x.remove();
  }
}
like image 76
Tomalak Avatar answered Jan 28 '23 19:01

Tomalak