Problem With Targetting :hover Dom With Queryselectorall
I am unable to get the background color of the li tags to change to red when my mouse hovers over them. excerpt from javascript.info Can use pseudo-classes as well: Pseudo-classe
Solution 1:
You might be better off adding a mouseenter
and mouseleave
event listener to the li
tags themselves rather than trying to select them based on the :hover
selector. When the document loads, none of them are being hovered over so the collection is empty.
let hover = document.querySelectorAll('li');
for (let elem of hover) {
elem.addEventListener('mouseenter', () => {
elem.style.backgroundColor = 'red'
})
elem.addEventListener('mouseleave', () => {
elem.style.backgroundColor = ''
})
};
<div><ul><li>1</li><li>2</li><li>3</li><li>4</li></ul><ul><li>a</li><li>b</li><li>c</li><li>d</li></ul></div>
Solution 2:
The problem is that you are not calculating that hover event in real-time. I mean, that way you are not subscribing to any event and querySelectorAll is just executed once. To do so you can try for example the event "onmousemove" so every time it fires it will calculate what you need.
This works:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8" /><metaname="viewport"content="width=device-width, initial-scale=1.0" /><metahttp-equiv="X-UA-Compatible"content="ie=edge" /><title>Document</title></head><body><div><ul><li>1</li><li>2</li><li>3</li><li>4</li></ul><ul><li>a</li><li>b</li><li>c</li><li>d</li></ul></div></body><script>window.onmousemove = () => {
let hover = document.querySelectorAll("li:hover");
console.log(hover);
for (let elem of hover) {
elem.style.background = "red";
}
};
</script></html>
Post a Comment for "Problem With Targetting :hover Dom With Queryselectorall"