0

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?

starball
  • 20,030
  • 7
  • 43
  • 238
Gee-on-woo
  • 51
  • 1
  • 8
  • 1
    Why don't you use pure CSS? – code Mar 17 '23 at 03:37
  • Does this answer your question? [Change :hover CSS properties with JavaScript](https://stackoverflow.com/questions/11371550/change-hover-css-properties-with-javascript) – showdev Mar 17 '23 at 03:48

3 Answers3

2

:hover is not something JS can affect. Use CSS instead:

.element:hover {
  background: red;
}

Note that event listeners can also do this, but they would not be as elegant as CSS:

div.addEventListener('mouseover', () => {
  div.classList.add('active');
});

div.addEventListener('mouseout', () => {
  div.classList.remove('active');
});

Try it:

const checkbox = document.querySelector('input');
const div = document.querySelector('div');

div.addEventListener('mouseover', () => {
  if (!checkbox.checked) {
    div.classList.add('active');
  }
});
div.addEventListener('mouseout', () => {
  if (!checkbox.checked) {
    div.classList.remove('active');
  }
});
label:has(:checked) + div:hover,
.active {
  background: red;
}

div {
  margin: 30px 0;
  height: 50px;
  width: 100px;
}
<label>Use CSS: <input type="checkbox" checked></label>

<div>Hover me!</div>
InSync
  • 4,851
  • 4
  • 8
  • 30
1

You can use a CSS variable to control the background on hover, which can also be set in JavaScript.

document.querySelector('button').addEventListener('click', e => {
  document.querySelector('.element').style.setProperty('--background', 'red');
});
.element:hover {
  --background: dodgerblue;
  background: var(--background);
}
<div class="element">
Hover over here
</div>
<button>Change hover color</button>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

An alternative to @inSync 's approach. In case , you need a pure JS solution , you could use the mouseover event as below :

const myDiv = document.querySelector(".mydiv");

myDiv.addEventListener("mouseover", (event) => {
  event.target.style.background = "Red";
});
<div class="mydiv">
  Hover over me !
</div>

Mouseover event : https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event

Bumhan Yu
  • 2,078
  • 1
  • 10
  • 20
Rohit
  • 115
  • 5