HTML table row click-able with link

You can not make a table row click-able using HTML alone. By click-able, I mean nesting an entire row inside an anchor tag, as follows:

HTML

  1. <a href="example.html"><tr><td>example table data</td></tr></a>

This is not valid mark-up as an anchor tag is an in-line element and therefore you should not nest a table row inside it.

Javascript to the rescue

You can how ever write a simple piece of Javascript to achieve the same end. jQuery makes this even simpler. The following snippet will link any table row to example.html.

jQuery

  1. $("tr").click(function(){
  2. window.location = "example.html";
  3. });

If you want to specify a specific table or table row, then you need to adjust the selectors accordingly. For example, if I have a table that has a class of "myclass", then I would use the following jQuery:

jQuery

  1. $(".myclass tr").click(function(){
  2. window.location = "example.html";
  3. });

Add a bit of style

The Javascript above achieves the desired functionality, but as it stands a user will not know that a row is clickable because it will look like any other table row. An easy way to make users aware that they can click on the row to change the cursor to a pointer and change the background colour of the row if the user hovers on the row. The snippet below will achieve this:

CSS

  1. tr:hover{
  2. cursor: pointer;
  3. background-color: #ccc;
  4. }

Of course, this will work on any table row. But if you want to specify a particular table, like we did in the jQuery example above, then simply make the CSS more specific, as follows:

CSS

  1. .myclass tr:hover{
  2. cursor: pointer;
  3. background-color: #ccc;
  4. }

Comments

wow, looks like wadmans nailed it again.

sry doesnt work

I think you have shared some of the very great information and i really appreciate your work.

great blog

I have index page in which I have added some data to table which are in div. When I click to any tr it's work fine, but when I appends table by using window.opener.document.getElementById('updateinfoch').innerHTML div, click to tr won't work. Please

But what if you want the link to open a new tap?

Add new comment