treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Change table Row background-color On click a link presented in td

  • Requirement : I have a link presented in a td of a table's tr. On click of this link, The complete row's background color should change to blue. I want to do it with CSS alone(Just checking whether can do it in CSS alone or not)

    I am able to change the link background color but not for tr. sample Code is :

    css used is :

    tr.test td a:hover
    {
    color: #FFFF00;
    background:#0000FF;
    }
    

    HTML Table is :

    <tr class='test'>
    <td> Data</td>
    <td> Age </td>
    <td> Name </td>
    <td> <a href="">Click Me 1</a>
    </tr>
    
    <tr class='test'>
    <td> A </td>
    <td> 23</td>
    <td> AAA</td>
    <td> <a href="">Click Me 2</a>
    </tr>
    

    Only 3rd TD getting effected but not entire TR. Please suggest on how to do it in CSS.

  • There's no selector we can use to select the parent of a hovered element.

    This is, however, possible in other ways. Here are your options:

    • Use a little JavaScript
    • wrap the whole row in an anchor
    • put the :hover rule on the table row
  • Thank you tbwiii. I am able to do it with javascript. Wrapping the whole row in an anchor is an interesting option. Will try that too. By mistake i kept hover in sample code. I want to do this onclick of the anchor in td.

  • Yeah then JavaScript is definitely the way to go, let us know if you need a hand with that.

  • Thank you I had completed it.