0

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?

Community
  • 1
  • 1
onmyway
  • 1,435
  • 3
  • 29
  • 53
  • Try providing a [mcve]. Add the minimal amount of HTML to demonstrate the problem. Make it a [live demo](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/). – Quentin Dec 19 '16 at 07:33

2 Answers2

2

In the first example you are getting the computed left margin, which will give you whatever the margin is after the stylesheet has cascaded.

In the second and third examples you are getting the left margin as specified in the style attribute. Since you are getting NaN this is, presumably, not set using the style attribute so is undefined.

Add parseInt to the code you used in the first place.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you for your response and help - much appreciated. Like this: `var test = parseInt(elementMargin.currentStyle || window.getComputedStyle(elementMargin));`? – onmyway Dec 19 '16 at 07:51
  • Don't forget the radix. – Quentin Dec 19 '16 at 07:53
  • I created this Fiddle: https://jsfiddle.net/onmyway/y4u752b8/10/ I would appreciate it if you could take a peek at what I am doing wrong. Thank you. – onmyway Dec 19 '16 at 08:07
  • You're running `parseInt` across the style object instead of the string with the number in it that you get from reading the `marginLeft` property of that object. – Quentin Dec 19 '16 at 08:20
  • Ohhhh! Thank you. – onmyway Dec 19 '16 at 08:34
0

To clarify the answer in case anyone else has the same question (thank you to Quentin):

var elementMargin = document.getElementById("main");
var style = elementMargin.currentStyle || window.getComputedStyle(elementMargin);

var oldValue = parseInt(style.marginLeft, 10);
console.log("Current marginLeft: " + oldValue);

Output: "Current marginLeft: 199px"

onmyway
  • 1,435
  • 3
  • 29
  • 53