Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: get css prop value with unit [duplicate]

Tags:

javascript

css

my code like this:

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

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

I want get '3vw'

Is it possible ?

like image 328
JeWoPeR Avatar asked Dec 09 '16 07:12

JeWoPeR


1 Answers

You can iterate document.styleSheets, .cssRules, if .selectorText matches element selector, select 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>
like image 139
guest271314 Avatar answered Oct 20 '22 07:10

guest271314