PhuongTT
PhuongTT

Reputation: 355

Get style's properties

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!

Upvotes: 2

Views: 136

Answers (3)

Stuart Kershaw
Stuart Kershaw

Reputation: 17701

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

Upvotes: 6

Ringo
Ringo

Reputation: 3967

Try this:

var element = document.getElementById('quicklink'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20418

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

Upvotes: 2

Related Questions