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.leftdocument.getElementById('my-div').offsetLeft
The problem is that both return null. Where is the problem?
The problem is that
someElement.style.leftonly 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: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.Working example