Reputation: 122
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.
Upvotes: 0
Views: 45
Reputation: 17457
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';
Upvotes: 7