Element.style.opacity does not return a value from CSS?


I am just starting with coding, and I am making a RGB guessing game with HTML, CSS and js to play with what I learned (an example http://www.rgbchallenge.com/ ).
If the user clicks the wrong color, I am setting the opacity of that element to 0, and I wanted to use an if statement to tell the program to check whether that element was already transparent (so that the score would not register further clicks on the same wrong element).

I have used the element.style.opacity property without trouble to set the opacity.
If I declare the value of the opacity in js, then it is returned correctly if called up later.
If I set the opacity in CSS, then js seems to not be able to return it. Just trying to print the value will result in nothing, and printing it as a string will return “[object Undefined]”.
After some testing, this seems to be the case for all properties in CSS (at least, I am getting the same results with color and backgroundColor.

I guess I can simply declare a value at the very start of the js, but I would like to understand if I am doing something wrong, or why this does not work. Can js not read the CSS?

my test code:


<!DOCTYPE html>
  <title>Opacity test</title>
  <link href="style.css" type="text/css" rel="stylesheet">

  <div id="color-banner"></div>
  <h2>The opacity value of the colored banner is:</h2>
  <h2 id="message1"></h2>
  <h2>The opacity value of the colored banner returned as string is:</h2>
  <h2 id="message2"></h2>

  <script src="script.js" type="text/javascript"></script>



#color-banner {
  width: 100%;
  height: 300px;
  background-color: red;
  opacity: 1;


//define variables for HTML elements
const colorBanner = document.getElementById("color-banner");
const testMessage1 = document.getElementById("message1");
const testMessage2 = document.getElementById("message2");

//sanity check that they were declared correctly:
colorBanner.style.backgroundColor = "blue";
testMessage1.innerHTML = "text shows up here";
testMessage2.innerHTML = "text also shows up here";

//test that opacity can be set >> WORKS!
//colorBanner.style.opacity = 0.5;

testMessage1.innerHTML = colorBanner.style.opacity;
testMessage2.innerHTML = toString(colorBanner.style.opacity);


the documentation:


should answer this question:

The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element’s inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets.

If some function/method is not behaving as expected, check the documentation.