3

How would I go about selecting a parent element when a child element is hovered over.

For example:

<table id="tb1">
<tr>
<td id="td1">make table red</td>
<td id="td2">make table yellow</td>
</tr>
</table>

Is there a way to select tb1 when td1 is hovered over using either the id or the class tags?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Middletone
  • 4,190
  • 12
  • 53
  • 74

2 Answers2

1

Unfortunately it is not possible to select a parent element when a child element is hovered using just CSS. This would defy the cascade in cascading style sheets. You could however accomplish this using JavaScript or one of the libraries such as jQuery easily enough.

If you were to use jQuery the following would provide the result that you are looking for:

http://jsfiddle.net/fSqSx/

DigiKev
  • 1,071
  • 3
  • 11
  • 19
  • I ended up using a combination of jquery and css to accomplish this. Each cell has a class name associated with it for the column. I do the row level changes with CSS and use jquery to dynamically rename the classes for the column's cells. The result is that when you hover over the column the cell changes it's class and thus it's colour. It works great. Just chang eit back when the cursor leaves the cell and it will work fine. – Middletone Feb 10 '11 at 04:38
0

Are the IDs of the table and the TDs always named like that? Assuming hovering over a TD generates an event with a function you could do

function highlightTable(){
  var tableID=this.id.replace('td','tb');
  document.getElementById(tableID).style.backgroundColor='#c0c0c0';
}
derekcohen
  • 1,514
  • 4
  • 17
  • 34
  • You should always abstract style, behaviour and markup. It is not good to add inline styles using JavaScript. – DigiKev Feb 11 '11 at 21:18