1

I have a situation where, depending on a variable value, I will want to modify EITHER the margin-top OR margin-bottom property of a div.

Apart from using an "if else", is there any way of doing it kinda like this :

var whichmargin="marginTop";
document.getElementById('myElement').style.whichmargin = '100px';

If you get what I mean lol ?

By the way, I am using vanilla JS rather than jQuery.

I don't want to use SetAttribute as I don't want to alter any other of the div style.

Any ideas much appreciated:

Chris Jones
  • 405
  • 1
  • 6
  • 17

1 Answers1

4

using the [] syntax:

var value = 'somethingelse';
var whichmargin = value === 'something' ? "marginTop" : "marginBottom";
document.getElementById('myElement').style[whichmargin] = '100px';
progysm
  • 1,072
  • 6
  • 7