Cannot Detect Margin with JavaScript DOM While It Is Set in CSS:
<div>
<div id="elem">
</div>
</div>
#elem{
margin:0;
}
console.log(document.getElementById('elem').style.marginLeft) //""
console.log(document.getElementById('elem').style["margin-left"]) //undefined
console.log($('#elem').css('margin-left')) //0px
What’s wrong?
What is the bullet-proof way to certainly detect margin without setting it via DOM?
Why does jQuery detect?
Can anyone explain in technical details why margin cannot be detected so I have an understanding?
Please remember, that CSS and DOM are different parts. Changes in CSS won’t change DOM content and vice-versa.
This means, that
element.style.marginLeft(DOM) returns the current value of thestyleattribute’smarginLeftproperty.Using
document.defaultView.getComputedStyle(element, '').getPropertyValue('margin-left')you can get the computed value instead.PS: That last way is -sadly- not compatible with some of the older browsers. You might be interested in a cross-browser version: http://cross-browser.com/x/lib/view.php?s=xGetComputedStyle