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?

6
  • What do you mean by "initial value"? Do you mean the CSS definition of "initial value", or something else? Commented Apr 29, 2016 at 9:04
  • you can try using the attr() to retrieve the value Commented Apr 29, 2016 at 9: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. Commented Apr 29, 2016 at 9: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. Commented Apr 29, 2016 at 9: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.left1 actually gives the inline styles. Commented Apr 29, 2016 at 9:34

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

4 Comments

I am curious. When you refer to inline styles do you mean the styles that are directly on the html?
Yes, javascript sets inline styles directly on the elements
Can I define longbox.style = getComputedStyle(longbox)?
No, you can't overwrite the element.style object completely, you can only set each style, but there is the cssText style, which can set multiple styles

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.