2

In my html file I have the following markup:

<div class="long_box">
    <div class="image1">  <img src="images/image1.png">  </div>
    <div class="image2">  <img src="images/image2.png">  </div>
    <div class="image3">  <img src="images/image3.png">  </div>
</div>

In the css file I have applied the following style rules:

.long_box {
    width: 3300px;
    height: 768px;
    position: absolute;
    left: 10px;
    top: 0;
}

In the javascript file I made a variable as:

var longbox = document.getElementsByClassName("long_box")[0];

Now when I try to recall the initial value of left of long_box as longbox.style.left, I get an empty string "". But after I change the left value with javascript, e.g. as as longbox.style.left = 100 + 'px and then recall it's value then I get 100px in the console. So,

How to get the initial value of style properties in javascript?

user31782
  • 7,087
  • 14
  • 68
  • 143
  • What do you mean by "initial value"? Do you mean the CSS definition of "initial value", or something else? – BoltClock Apr 29 '16 at 09:04
  • you can try using the attr() to retrieve the value – Dhaval Chheda Apr 29 '16 at 09:05
  • @BoltClock By initial value I mean the values assigned in the css file -- which might get altered by javascript later. And after altering them I can somehow access them -- Maybe because `this.style.left = 100 + 'px'` adds inline styles. – user31782 Apr 29 '16 at 09:05
  • You can't get the old style back if you've already changed it, or rather, you could, but that would require parsing all stylesheets to look for that style, or storing the old value before you change it. – adeneo Apr 29 '16 at 09:10
  • @adeneo I don't want the old styles after changing them. I thought that `this.style.left` only works after changing the value of left. But now I got that `this.style.left`1 actually gives the inline styles. – user31782 Apr 29 '16 at 09:34
  • This question is unfortunately worded. Is there a way to get the initial value of a style as it would be given by the CSS initial keyword, which sets the property back to how it would be in the CSS spec? – Rob Smallshire Jul 29 '19 at 08:47

1 Answers1

8

Javascripts element.style only returns inline styles, for other styles, for instance set in a stylesheet, you'd have to use getComputedStyle

var longbox = document.getElementsByClassName("long_box")[0];

var styles  = window.getComputedStyle(longbox);

var lef     = styles.getPropertyValue("left");
adeneo
  • 312,895
  • 29
  • 395
  • 388