0

How can the CSS property of an element (e.g margin-left) be retrieved and then some value can be added to it, and the element gets altered with the updated value.

Suppose:

var element = document.getElementById("myElement");
var value = element.style.margin-left;

//How to do something like this?
var updatedValue = value + 10;
element.style.margin-left = updatedValue;

As, style.margin-left accepts values in pixels. How to retrieve the current value, then add something to it, then update the element with the same? Thank you.

2
  • Do you have option to use jQuery? Commented Nov 12, 2015 at 17:48
  • No. jQuery is out of this scenario. Commented Nov 12, 2015 at 17:50

1 Answer 1

7

Just use parseInt or parseFloat to convert the string to a number, then re-apply the px.

var value = parseInt(element.style.marginLeft);
element.style.marginLeft = (value + 10) + 'px';

Note: this will work for other units, such as em, %, etc.

Per @ScottKaye in the comments, here is an example using getComputedStyle, if the styles are applied via a stylesheet instead of in the style attribute on the DOM element:

var value = parseInt( window.getComputedStyle(element).marginLeft );
element.style.marginLeft = (value + 10) + 'px';
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting a null value, when I'm trying to parse the margin.style.marginLeft
Is margin.style.marginLeft correct (i.e. is the variable named margin)?
@AnkitNeo Unless margin-left is set explicitly in the inline style, you can't get stylesheet values like this. Take a look at getComputedStyle if this is what you need.
Good point @ScottKaye, I added an example using getComputedStyle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.