Trying:
document.querySelector(".element:hover").style["background"] = "red";
The code didn’t work for me because of the ":hover".
In order to change the background-color of the element when it has hovered, what can I do?
Trying:
document.querySelector(".element:hover").style["background"] = "red";
The code didn’t work for me because of the ":hover".
In order to change the background-color of the element when it has hovered, what can I do?
3
Answers
:hover
is not something JS can affect. Use CSS instead:Note that event listeners can also do this, but they would not be as elegant as CSS:
Try it:
You can use a CSS variable to control the background on hover, which can also be set in JavaScript.
An alternative to @inSync ‘s approach.
In case , you need a pure JS solution , you could use the
mouseover
event as below :Mouseover event : https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event