Javascript: get css prop value with unit

my code is:

#image_1 { position: absolute; top: 3vw; } 

My attempt: http://jsfiddle.net/z8k6t3fb/1/

I want to get '3vw'

Is it possible?

+5
source share
1 answer

You can iterate through document.styleSheets , .cssRules , if .selectorText matches the element selector, select a rule from .style property

 window.onload = function() { var element = document.getElementById("image_1"); var prop = "top"; var styles = document.styleSheets; for (var j = 0; j < styles.length; j++) { var rules = document.styleSheets[j].cssRules; for (var i = 0; i < rules.length; i++) { if (rules[i].selectorText === "#" + element.id) { console.log(rules[i].style[prop]) } } } } 
 #image_1 { position: absolute; top: 3vw; } 
 <div id="image_1">hello</div> 
+5
source

Source: https://habr.com/ru/post/1261029/


All Articles