Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  177] [ 7]  / answers: 1 / hits: 57440  / 12 Years ago, sat, december 8, 2012, 12:00:00

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?


More From » css

 Answers
2

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


[#81533] Friday, December 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blair

Total Points: 384
Total Questions: 108
Total Answers: 86

Location: Northern Ireland
Member since Tue, May 5, 2020
4 Years ago
blair questions
Sat, Feb 12, 22, 00:00, 2 Years ago
Wed, Aug 25, 21, 00:00, 3 Years ago
Sat, Jul 10, 21, 00:00, 3 Years ago
Tue, Aug 25, 20, 00:00, 4 Years ago
;