0

I'd like to get the evaluated output of a css calc that refers to vars from parent elements. For example, the example below should log 21 not NaN. Is there a way to do this?

let outer = document.getElementById('outer')
let inner = document.getElementById('inner')

outer.style.setProperty('--A',7)
inner.style.setProperty('--B',3)
inner.style.setProperty('--C','calc (var(--A) * var(--B))')

let a = Number(getComputedStyle(inner).getPropertyValue('--C'))

console.log(a)
//is there a way to log '21' as opposed to NaN?
<div id="outer">
  <div id="inner">
  </div>
 </div>
 
 

10
  • 1
    getPropertyValue returns calc (7 * 3) so you could write a function that performs this calculation and returns the result. Obviously the Number constructor doesn't know what to do with this string value which is why you are getting NaN. Commented Apr 6, 2022 at 14:01
  • @DM true, thanks, but I am wondering if there is a way to get the evaluated result without having to re-lookup --A and --B Commented Apr 6, 2022 at 14:03
  • 1
    I don't think you have to look up --A or --B. Calling getPropertyValue('--C') already substitutes their values into the result it returns to you. Now, if --A or --B themselves had a calc(...) in them, then yes, you'd need to go compute them first with this approach. Commented Apr 6, 2022 at 14:04
  • 1
    stackoverflow.com/questions/48903509/… might help Commented Apr 6, 2022 at 14:07
  • 2
    This question should really help stackoverflow.com/questions/56229772/… Commented Apr 6, 2022 at 14:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.