0

I have an element with the following style:

p {
  color: 'red';
}

When I'm trying to get the element color by running the following code:

  const styles = window.getComputedStyle(pElem);
  const value = styles.getPropertyValue('color');

I'm getting the color in RGB format. How I can get the real value - 'red'?

I need this functionality for testing purposes, for example:

expect(p).toHaveStyle({color: 'red'});
undefined
  • 6,366
  • 12
  • 46
  • 90
  • 2
    [Does this help](https://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript)? – Andy Sep 02 '17 at 18:27
  • [Here's an example using that code](https://jsfiddle.net/0xfs2fgg/5/). Note it doesn't appear to work with quotes in the rules like yours. – Andy Sep 02 '17 at 18:39
  • Thanks! That's working, but a little verbose, I will wait for more answers. – undefined Sep 02 '17 at 18:42
  • what do you mean with verbose? – Felix Sep 02 '17 at 18:43
  • It feels "hacky". – undefined Sep 02 '17 at 18:43
  • 1
    Remember it has to cover all browser types. Looking at the comments under the accepted answer it at least covers FF and Chrome. What else were you expecting? – Andy Sep 02 '17 at 18:47
  • OK, can you add this as an answer, please? – undefined Sep 02 '17 at 18:49
  • 1
    The RGB value *is* the "real" value - colour names are just aliases for certain common colours and get converted to the corresponding RGB value so the browser can understand it. Its not possible to reverse this by turning an RGB value back into a colour name, because most RGB values don't have corresponding colour names, so the only way is to read the value directly from the stylesheet as @Andy suggested. – FluffyKitten Sep 02 '17 at 22:22

0 Answers0