Sé que puede obtener las propiedades personalizadas :root o html usando window.getComputedStyle(document.body).getPropertyValue('--foo') , pero me preguntaba cómo obtendría el valor de una propiedad de ámbito de clase.
Por ejemplo:
body { --background: white; } .sidebar { --background: gray; } .module { background: var(--background); } ¿Cómo obtendría getPropertyValue('--background') de .sidebar , que me devolvería gray en lugar de white ? ¿Estoy yendo en la dirección equivocada al querer hacer esto (tengo una biblioteca que necesita los colores que se le pasan a través de JS, y ya están definidos como propiedades personalizadas)?
Investigar:
.sidebar y obtenerlo de esa manera, pero no parece confiable en caso de que no exista dicho elemento.const sideBarNodeRef = document.querySelector(".sidebar"); const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.style.backgroundColor:null or const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.getPropertyValue('background-color'):nullPuede hacerlo como su "Investigación 1", solo verifique si el elemento existe para evitar errores.
Tenga en cuenta que si una variable no está definida, heredará del padre.
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>