2

I have a question about getting DOM style by javascript.

#quicklink {
    position: absolute;
    top: 500px;
    left: 500px;
}

<div id="quicklink" class="draggable">
    <img class="menu_icon" src="4a.png" src="" />                   
</div>

When i try to get top of element by this code. Why it always has empty string value?

var quicklink = document.getElementById('quicklink');
console.log(quicklink.style.top); // string value ??? 

Thank you!

PhuongTT
  • 335
  • 1
  • 8
  • 19
  • possible duplicate of [How to retrieve a style's value in javascript?](http://stackoverflow.com/questions/2664045/how-to-retrieve-a-styles-value-in-javascript) – RienNeVaPlu͢s Dec 19 '13 at 04:32

3 Answers3

6

It's because the styling doesn't reside in the DOM as an attribute on that element ID. You can try getComputeStyle() to access styles applied through separate CSS.

var elem1 = document.getElementById("elemId"); 
var style = window.getComputedStyle(elem1, null);

MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle

W3C: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-OverrideAndComputed-h3

Stuart Kershaw
  • 16,831
  • 6
  • 37
  • 48
  • Can you explain to me why it always log with empty string value? – PhuongTT Dec 19 '13 at 04:37
  • 1
    The doc explains that `getComputedStyle()` gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain. So probably this may the reason of empty string of not applying active style sheet till then. – Kunj Dec 19 '13 at 05:18
2

Try this

function getCssProperty(elmId, property){
   var elem = document.getElementById(elmId);
   return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var top = getCssProperty("quicklink", "top");
console.log(top)

DEMO

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
1

Try this:

var element = document.getElementById('quicklink'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');
Ringo
  • 3,795
  • 3
  • 22
  • 37