Search code examples
javascripthtmltablesorter

Is it bad to supplement colspanned table with hidden cells?


I have been developing some sorting and selecting functions on a table and I found it very difficult to orient in a table with colspanned cells. I simply added the spanned cells and hid them. It looks good, it works with my js, great for indexing, but I would like to know if that is a legit approach.

.stuffing {
    display: none;
}
<table>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td colspan="3">1</td>
        <td class="stuffing"></td>
        <td class="stuffing"></td>
        <td>4</td>
    </tr>
</table>
document.querySelectorAll('table tr:nth-child(1) td')[3].innerHTML // "4"
document.querySelectorAll('table tr:nth-child(2) td')[3].innerHTML // "4"

If it wasn't for the hidden cells, I would have to access the value by [1].

The jQuery tablesorter iteself doesn't sort properly on tables with colspan.


Some tags to help people find this issue.
Retrieve “correct” index of table affected by colspan or rowspan.
Find each table cell's “visual location”.


Solution

  • Your technique certainly improves programmatic access to tables having colspans.

    If your colspan length is limited, you could avoid using hidden classes like this:

    td[colspan="2"]+td,
    td[colspan="3"]+td, td[colspan="3"]+td+td,
    td[colspan="4"]+td, td[colspan="4"]+td+td, td[colspan="4"]+td+td+td {
      display: none;
    }
    

    This throws an error in Safari:

    document.querySelectorAll('table tr:nth-child(2) td')[3].innerHTML
    

    This is resolved by indexing directly into the table using the rows and cells collections (both 0-based):

    var tb= document.querySelector('table');
    tb.rows[0].cells[3].innerHTML;  //4
    tb.rows[1].cells[3].innerHTML;  //4