4

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?

2
  • you want empty rows gone too so why is an empty row there in the desired result figure.. Commented Dec 20, 2011 at 5:50
  • @3nigma I only want the outside empty rows and columns removed. Empty rows and columns in between content is desired. Commented Dec 20, 2011 at 5:53

1 Answer 1

9
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();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.