When you use jQuery's css()
function with a single argument, it gets the currently applied (i.e., after stylesheets, inline styles, etc. are applied) style property matching the passed argument via the getComputedStyle()
function call.
Thus, when you call that function, you get the browser's internal representation of the CSS value originally set. Let's show that with an example, but using JavaScript against the DOM/CSSOM:
window.onload = function () {
var kermit = document.getElementById('kermit');
console.log('style: ', kermit.style.backgroundColor);
console.log('computed: ', window.getComputedStyle(kermit).backgroundColor);
};
<div id="kermit" style="background-color: green; color: #fff">It ain't easy</div>
Depending on your browser, it should show green
as the first log entry and rgb(0, 128, 0)
for the second. I say "depending on your browser" because, as is explained in jQuery's css documentation:
Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).
The easiest way to get what you want is ... well, beyond using a library as indicated by xxxmatko ... to create a mapping between the color values retrieved via getComputedStyle
and the names. Note that this wouldn't tell you if the author of the stylesheet or whatever originally specified the color name, or some other value that happens to have the same RGB values.
window.onload = function () {
var colorMap = {
'rgb(0, 128, 0)': 'green'
};
var kermit = document.getElementById('kermit');
var computed = window.getComputedStyle(kermit).backgroundColor;
console.log('color name: ', colorMap[computed]);
};
<div id="kermit" style="background-color: green; color: #fff">It ain't easy</div>
Creating that map for the rest of the named colors (and the different corresponding color formats) is left as an exercise for the reader.