The Right Way to hyperlink a row in an HTML table
I’m currently in the process of rewriting a user interface to remove most of the jQuery and other stuff like datatables and similar, and replace them with straight HTML, CSS, and some django-tables2 and django-unicorn magic to provide the filtering components.
One feature of the tables for this specific app is that in most cases, the UX expectation is to click on a row of a table, and be taken to the detail page for that row. That turns out to be …. interesting.
I’ve seen (and even be guilty of) the sin of simply wrapping the tr in an anchor tag:
<table> <a href="#"><tr><td>Column 1</td><td>Column 2</td><td>Column 3</td></tr></a> </table>
But turns out that even if it works, this is not at ALL allowed in the HTML spec - the permitted content for a ‘table’ tag does not allow an ‘a’ tag, only ‘caption’, ‘colgroup’ ‘thead’, ‘tbody’, ‘tr’, or ‘tfoot’.
We can just use ‘div’ tags instead of the table/td tags, and style them as a table using CSS, instead:
<div style="display: table"> <a href="#"><div style="display: table-row"><div style="display: table-cell">Column 1</div><div style="display: table-cell">Column 2</div><div style="display: table-cell">Column 3</div></div></a> </div>
Or using TailwindCSS (which I am, in this case at least):
<div class="table"> <a href="#"><div class="table-row"><div class="table-cell">Column 1</div><div class="table-cell">Column 2</div><div class="table-cell">Column 3</div></div></a> </div>
Since my tables are mostly handled by django-tables2, getting this to work in this spec-compliant way was just a matter of modifying my custom table template. Sure, it’s not strictly required, but it gives me a warm fuzzy feeling when I’m able to do things more in line with published web standards.