using the [] syntax:
var value = 'somethingelse';
var whichmargin = value === 'something' ? "marginTop" : "marginBottom";
document.getElementById('myElement').style[whichmargin] = '100px';
문제
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:
해결책
using the [] syntax:
var value = 'somethingelse';
var whichmargin = value === 'something' ? "marginTop" : "marginBottom";
document.getElementById('myElement').style[whichmargin] = '100px';