Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Check element rendered opacity value

Let's say I have the following DOM. The element opacity is 1, but since it is wrapped by a parent div, it will render with opacity 0.1:

let el = document.getElementById("element");
console.log(document.defaultView.getComputedStyle(el)["opacity"]);
<div style="opacity:0.1">
  <div id="element">Check Me</div>
</div>

The result is still 1.

I thought of looping through the element's hierarchy and check to see if somewhere in the chain an ancestor have a different opacity and save the minimum value, but I'm thinking that there got to be an easier way.

How can I get the rendered opacity value?

like image 773
Shlomi Schwartz Avatar asked Nov 29 '25 15:11

Shlomi Schwartz


1 Answers

I thought of looping through the element's hierarchy...and save the minimum value

It's worse than that. :-) If ancestors have opacity, the values are combined (I believe they're multiplied together), note how the second one is lighter than the first:

<div style="opacity:0.3">
  <div>Check Me</div>
</div>
<div style="opacity:0.3">
  <div style="opacity:0.5">
    <div>Check Me</div>
  </div>
</div>

So I think you have to go through the hierarchy and multiply the values toether:

let element = document.getElementById("element");
let opacity = 1;
while (element && element.nodeType === 1) {
  const op = getComputedStyle(element).opacity;
  if (op) {
    opacity *= parseFloat(op);
  }
  element = element.parentNode;
}
console.log("Effective opacity: ", opacity);
<div style="opacity:0.1">
  <div>Check Me - for comparison with the one below</div>
</div>
<div style="opacity:0.2">
  <div style="opacity:0.5">
    <div id="element">Check Me</div>
  </div>
</div>
like image 97
T.J. Crowder Avatar answered Dec 02 '25 03:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!