How to get the CSS left-property value of a div using JavaScript
css, javascript
Solution
The problem is that `someElement.style.left` only work if you have inline style. Since you apply your styling through a stylesheet, you will not be able to fetch the value the way you expect.
You have a couple of other approaches you could take to get the value through JavaScript:
window.getComputedStyle:
It is possible to get the computed style of an element using `window.getComputedStyle`, the problem is that it has quite limited support (IE9+). If you still want to use it you could wrap it up in a function to make it a bit easier to get each property:
function getCssProperty(elmId, property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var left = getCssProperty("my-div", "left");
Working example
jQuery (or some other library):
Another option would be to use a JavaScript library like jQuery (or whatever you prefer), which will provide you with a cross-browser solution to get the value.
With jQuery you could use the `.css()` method to read the CSS-property of the element.
$(function () {
var left = $("#my-div").css("left");
});
Working example
Problem
My CSS rule looks like this: ``` #my-div{ display: none; position: absolute; left: -160px; bottom: -150px; } ``` I'm trying to get value of the left-property like this: - `document.getElementById('my-div').style.left` - `document.getElementById('my-div').offsetLeft` The problem is that both return `null`. Where is the problem?