2

I am trying to make a chrome extension that finds the original background color of the pressed element.
I mean the background color that was before user hovered and the :hover selector (maybe) changed it.
I tried to use document.styleSheets but it gives me an error.

Example

window.addEventListener("click",function(e){
  pressedElement = e.target;
  console.log(window.getComputedStyle(pressedElement,null).backgroundColor);
  //return blue but I want the background before hover changes (green,yellow,red in this case)
});
div{
  height:100px;
  width:100px;
}
div:hover{
  background-color:blue !important;
}
<div style="background-color:green;">1</div>
<div style="background-color:yellow;">2</div>
<div style="background-color:red;">3</div>
window.getComputedStyle(pressedElement,null).backgroundColor return the current background color (blue in this case), but I want the background color before :hover changes (red, yellow or green in this case).
ATP
  • 2,939
  • 4
  • 13
  • 34

1 Answers1

2

Just replace the element with itself, which forces the hover state to update, then calculate the style:

window.addEventListener("click",function(e){
  const target = e.target;
  target.parentNode.replaceChild(target, target)
  const color = window.getComputedStyle(target,null).backgroundColor;
  console.log(color);
  return color;
});
div{
  height:100px;
  width:100px;
}
div:hover{
  background-color:blue !important;
}
<div style="background-color:green;">1</div>
<div style="background-color:yellow;">2</div>
<div style="background-color:red;">3</div>
cyr_x
  • 13,987
  • 2
  • 32
  • 46