I am trying to parse the marginLeft
property value of an HTML
element using JavaScript
, but I am not sure what I am doing wrong.
I have used both these methods (with or without the ,10
), but get "Current marginLeft: NaN
" with my console.log
:
var elementMargin = document.getElementById("main");
var style = elementMargin.currentStyle || window.getComputedStyle(elementMargin);
// tried this
var oldValue = parseInt(document.getElementById("main").style.marginLeft, 10);
console.log("Current marginLeft: " + oldValue);
// or this
var oldValue = parseInt(document.getElementById("main").style.marginLeft);
console.log("Current marginLeft: " + oldValue);
When I do a straightforward read and console.log
of the property value, I do not get an error:
var elementMargin = document.getElementById("main");
var style = elementMargin.currentStyle || window.getComputedStyle(elementMargin);
console.log("Current marginLeft: " + style.marginLeft);
I get the output "Current marginLeft: 199px"
This is based on this post: Get a number for a style value WITHOUT the "px;" suffix
What am I doing wrong?