How can JavaScript change CSS :hover
properties?
For example:
HTML
JavaScript
x
7
1
<table>
2
<tr>
3
<td>Hover 1</td>
4
<td>Hover 2</td>
5
</tr>
6
</table>
7
CSS
JavaScript
1
4
1
table td:hover {
2
background:#ff0000;
3
}
4
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:
JavaScript
1
2
1
document.getElementsByTagName("td").style.background="#00ff00";
2
But I don’t know of a .style
JavaScript equivalent for :hover
.
Advertisement
Answer
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.
JavaScript
1
11
11
1
var css = 'table td:hover{ background-color: #00ff00 }';
2
var style = document.createElement('style');
3
4
if (style.styleSheet) {
5
style.styleSheet.cssText = css;
6
} else {
7
style.appendChild(document.createTextNode(css));
8
}
9
10
document.getElementsByTagName('head')[0].appendChild(style);
11