Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast selection of table columns with jQuery

We have a large HTML table (maybe 100x100 cells). Selecting rows is pretty fast as we can simply select all TDs in a specific TR. But selecting columns with the help of jQuery and nth-child is much slower. Are there any faster alternatives for column selection? How about pseudo classes for every column (like class="column-1", and so on)? What is your experience with this?

like image 943
tok Avatar asked Nov 06 '22 05:11

tok


1 Answers

Are there any faster alternatives for column selection?

I would recommend using the much-ignored COLGROUP/COL tags, as per the original W3C HTML spec. Copy-and-paste this code into a dummy HTML page and see for yourself the magic of COLGROUPs!

<table id="mytable">
  <caption>Legend</caption>
  <colgroup>
    <col style="background-color: #f00;"/>
    <col/>
    <col/>
  </colgroup>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <td>cell 1,1</td>
      <td>cell 1,2</td>
      <td>cell 1,3</td>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>footer 1,1</td>
      <td>footer 1,2</td>
      <td>footer 1,3</td>
    </tr>
  </tbody>
</table> 

TFOOT tags go before TBODY tags. COLGROUPs have COLs for each column.

The advantage of this is that styling to a COL inside a COLGROUP will cascade to all of the columns in a table. Background colors, for instance. It never ceases to amaze me how many people have absolutely no idea of this trick, even though the HTML spec is out there for anybody to read and digest.

like image 142
Matt Brock Avatar answered Nov 09 '22 04:11

Matt Brock