1

How can I get the inline style of a custom CSS var from an element?
I can easily get the width or any other traditional styles but get an error when I try to get the custom inline style. Is there a way to extract this style data? Thank you in advance for any help provided. No jQuery Please.

var styleDivWidth = document.getElementById('myId').style.width;
console.log(styleDivWidth);

/*
var styleDivRotation = document.getElementById('myId').style.--rotation;
console.log(styleDivRotation);
*/
.myClass{
background-color:red;
float:left; 
--rotation: 45deg;
transform: rotate(var(--rotation));
margin:20px;  
}
<div id="myId" class="myClass" style="width:100px; height:100px;
 --rotation:-45deg;">
Jonny
  • 1,311
  • 1
  • 13
  • 25
  • you probably have to get the value of the `transform` property and parse out the value – zgood Nov 06 '19 at 17:48
  • Ill try that thank you – Jonny Nov 06 '19 at 17:49
  • 1
    note that inline styles are always more specific that external one so you question can simply be *how to read value of custom property* and the answer is easier that what you are getting here. A simple computedStyle and you get it – Temani Afif Nov 06 '19 at 18:53
  • thank you @TemaniAfif you were right i found a much better solution with the links you posted at the top.. var styleRotation = document.getElementById('myId').style.getPropertyValue('--rotation'); – Jonny Nov 06 '19 at 19:07

3 Answers3

1
var rotation = document.getElementById("myId").style.cssText.split("--rotation:")[1];
rotation = rotation.substring(0, rotation.length - 1);
console.log(rotation);
Adina E
  • 151
  • 6
1

You can extract this by parsing the cssText property.

Here's some code and JsFiddle below:

const cssText = document.getElementById('myId').style.cssText;
console.log(cssText);
const rotationProp = cssText.split("; ").find(style => style.includes("rotation"));
console.log(rotationProp);

const rotationValue =  rotationProp.slice(rotationProp.indexOf(":") + 1, rotationProp.indexOf(";"));
console.log(rotationValue);

JsFiddle: https://jsfiddle.net/2ajp1cug/

Barzev
  • 402
  • 3
  • 14
1

I made a function that will do it :

function getAttributeValueFromStyles(stylesText, attributeName){
   var attrParts = stylesText.split(';');
   var attrIndex = attrParts.findIndex(function(part){
    return part.split(':')[0] === attributeName;
   });
   return attrParts[attrIndex].split(':')[1];
}
const element = document.querySelector('#test');
const style = element.getAttribute("style");
var attrValue = getAttributeValueFromStyles(style, "--rotation");
console.log(attrValue);
<div id="test" style="backgroud:red;--rotation:-45deg;color:white;">
 
</div>
  • I don't know but may be there is another way to do it with js available methods.
Ilia Afzali
  • 399
  • 1
  • 6