Real problematic
Write a function that returns the color value from any CSS color OR from a color defined by a class
Initial formulation
I would like to know if a string passed in parameter to my function is a color - answering only that would already be great - and then to know its hex value.
So I have defined a regex to find out if the string is something like #fff
or also rgb(0,0,0)
, but it doesn't catch CSS standard colors such as black
and white
. Should I test each color name or is there any way or preexisting function to do that ? Thanks.
Solution personally used
- If you want dot-preceded class names 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;
}
}
Usage examples:
getColor('yellow')
getColor('#abc')
getColor('rgb(1,2,3)')
getColor('.myClass .myOtherClass')
Solution based on mplungjan's answers
- If you want plain class names such as "myClass"
Search if a class with this name exists using this answer: https://stackoverflow.com/questions/983586/...
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;
}
}
Usage examples:
getColor('#abc')
getColor('myClass')