Remove empty rows and columns in a table using jQuery

Suppose I have a table like this:

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

I want to remove all outer rows and columns that are empty. The above example will be summarized as follows:

 +-----+ |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 quickly remove up to 30 extraneous rows and columns.

Is there a quick and half decent way to do this?

+4
source share
1 answer
 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 can use this as an inner loop, maybe this is a little faster:

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

Source: https://habr.com/ru/post/1387148/


All Articles