Home > Enterprise >  From .class scope, get CSS custom property (variable) value using javascript
From .class scope, get CSS custom property (variable) value using javascript

Time:11-18

I know you can get the :root or html custom properties using window.getComputedStyle(document.body).getPropertyValue('--foo'), but I was wondering how you would get the value from a class scoped property?

For example:

body {
  --background: white;
}
.sidebar {
  --background: gray;
}
.module {
  background: var(--background);
}

How would I get getPropertyValue('--background') from .sidebar, which would return me gray instead of white? Am I going the wrong direction by wanting to do this (I have a library that needs the colors passed to it through JS, and they are already defined as custom properties)?

Research:

  1. I could probably query for an element with .sidebar and get it that way, but it does not seem reliable in case no such element exists.
  2. Seems like I can list all properties (https://css-tricks.com/how-to-get-all-custom-properties-on-a-page-in-javascript/), but this process seems cumbersome.

CodePudding user response:

const sideBarNodeRef = document.querySelector(".sidebar");

const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.style.backgroundColor:null

or

const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.getPropertyValue('background-color'):null

CodePudding user response:

You can do it like your "Research 1.", just check if the element exists to avoid errors.
Notice that if a variable is not defined, it will inherit from the parent.

function getCssVar(selector, style) {
  var element = document.querySelector(selector)
  
  // Exit if element doesn't exist
  if(!element) return false
  
  // Exit if variable is not defined
  if(!getComputedStyle(element).getPropertyValue(style)) return false
  
  console.log(`${selector} : ${getComputedStyle(element).getPropertyValue(style)}`) 
}

getCssVar('.exist-and-has-variable', '--background')
getCssVar('.exist-and-no-variable', '--background')

getCssVar('.child-with-variable', '--background')
getCssVar('.child-without-variable', '--background')

getCssVar('.dont-exist', '--background')
:root {
  --background: white;
}
.exist-and-has-variable {
  --background: gray;
}
.child-with-variable {
  --background: red;
}
<div class="exist-and-has-variable">
  <div class="child-with-variable"></div>
  <div class="child-without-variable"></div>
</div>

<div class="exist-and-no-variable">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related