javascripthtmlcssdhtml

Change :hover CSS properties with JavaScript


How can JavaScript change CSS :hover properties?

For example:

HTML

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

CSS

table td:hover {
background:#ff0000;
}

How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:

document.getElementsByTagName("td").style.background="#00ff00";

But I don't know of a .style JavaScript equivalent for :hover.


Solution

  • Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.

    var css = 'table td:hover{ background-color: #00ff00 }';
    var style = document.createElement('style');
    
    if (style.styleSheet) {
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }
    
    document.getElementsByTagName('head')[0].appendChild(style);