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:

2
  • What's wrong with an if-else statement? Commented Mar 19, 2014 at 15:50
  • Nothing wrong with an if-else, just a bit less code this way :) Commented Mar 19, 2014 at 16:06

1 Answer 1

4

using the [] syntax:

var value = 'somethingelse';
var whichmargin = value === 'something' ? "marginTop" : "marginBottom";
document.getElementById('myElement').style[whichmargin] = '100px';
Sign up to request clarification or add additional context in comments.

1 Comment

Yesss!!! Thank you so much - I KNEW I had done it before but couldn't remember :) MUCH Appreciated.

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.