Is there a way to get the hex value of any CSS color?

Real problematic

Write a function that returns a color value from any CSS color OR from a color defined by a class

Initial wording

I would like to know if the string passed in the parameter of my function matches the color β€” the answer is just that would be great β€” and then know its hexadecimal value.

So, I defined a regex to find out if a string is something like #fff or also rgb(0,0,0) , but it does not recognize standard CSS colors like black and white . Do I have to test every color name or is there any way or a pre-existing function exists? Thanks.

Personal solution

  • If you want class names preceding dots, such as ".myClass"
 function getColor(classOrColor) { if(classOrColor[0] === '.') { var temp = $('<div id="temp" style="display:none;" class="'+ classOrColor.split('.').join(' ') + '"/>').appendTo('body'); var color = temp.css('color'); temp.remove(); return color; } else { return classOrColor; } } 

Examples of using:

 getColor('yellow') getColor('#abc') getColor('rgb(1,2,3)') getColor('.myClass .myOtherClass') 

Mplungjan answer based solution

  • If you want simple class names such as "myClass"

Search if a class with that name exists with this answer: https://stackoverflow.com/a/316829/

Then call the same function (with minor modification)

 function getColor(classOrColor) { if(classExists(classOrColor)) { var temp = $('<div id="temp" style="display:none;" class="'+ classOrColor + '"/>').appendTo('body'); var color = temp.css('color'); temp.remove(); return color; } else { return classOrColor; } } 

Examples of using:

 getColor('#abc') getColor('myClass') 
+4
source share
1 answer

You can use getComputedStyle - this does not work on IE8 and below.

Please see the answer to the Javascript function for converting color names to hexadecimal codes for better coverage than mine (saw it after I wrote it)

Demo

 function getRGB(str){ var elem = document.createElement("div"); elem.style.display="none"; elem.style.color=str; document.body.appendChild(elem); return window.getComputedStyle(elem,null).getPropertyValue("color"); } alert(getRGB("red")); 
+4
source

All Articles