Shlomi Schwartz
Shlomi Schwartz

Reputation: 8903

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?

Upvotes: 3

Views: 816

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

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>

Upvotes: 4

Related Questions