Q:

How to get the background color of an element (set to RGBA) in Javascript?

I have an element with the Id box, which has a background color set to rgba(0, 0, 0, 0.3) on a white background. Like so:

#box {
  width: 100px;
  height: 100px;
  margin: 10px;
  background-color: rgba(0, 0, 0, 0.3);
}
<div id="box"></div>

Using a color picker, I can see that the box's color is in hex is #b2b2b2. Now, what I want to know is there any way to get this hex code using JavaScript
without convert RGBA to hex format? I read about getComputedStyle function, but could not get it to work. Any help is greatly appreciated.

A:

I will consider this answer where I am detailing how the color is calculated between two layers to write the following script.

/* Utility function that you can easily find in the net */
function extractRgb (css) {
  return css.match(/[0-9.]+/gi)
}
function rgbToHex(r, g, b) {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
/**/

var c = window.getComputedStyle(document.getElementById('box')).backgroundColor;
c = extractRgb(c);

for(var i=0;i<3;i++)
  c[i] = parseInt(c[i]*c[3] + 255*(1 - c[3])); /* Check the linked answer for details */

console.log(rgbToHex(c[0],c[1],c[2]) )
#box {
  width: 100px;
  height: 100px;
  margin: 10px;
  background-color: rgba(0, 0, 0, 0.3);
}
<div id="box"></div>

The script can easily be improved but the main idea is the formula uses to calculate the result between two colors:

ColorF = (ColorT*opacityT + ColorB*OpacityB*(1 - OpacityT)) / factor
ColorF is our final color. ColorT/ColorB are respectively the top and bottom colors. opacityT/opacityB are respectively the top and bottom opacities defined for each color:
The factor is defined by this formula OpacityT + OpacityB*(1 - OpacityT).

