wagtail wagtail - 1 year ago 198
Javascript Question

Change :hover CSS properties with JavaScript

I need to find a way to change CSS :hover properties using JavaScript.

For example, suppose I have this HTML code:

<td>Hover 1</td>
<td>Hover 2</td>

And the following CSS code:

table td:hover {

I would like to use JavaScript to change the <td> hover properties to, say, background:#00ff00. know I could access the style background property using JavaScript as:


But I don't know of a JavaScript equivalent for :hover. How do I change these <td>'s :hover background using JavaScript?

Your help is greatly appreciated!

Answer Source

Pseudo elements (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 }';
style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download