0

I have written a function that using jquery .css and simply passes the element, css property and the css value.

Here is the function:

function addCss(element, cssProperty, cssValue) {
   $(element).css({ cssProperty: cssValue }); 
}

And here's an example usage:

addCss('.container','flex-direction', 'row');

For some reason its doing nothing.

I'm I missing something or is the syntax wrong?

2 Answers 2

3

Try $(element).css({ [cssProperty]: cssValue });

Sign up to request clarification or add additional context in comments.

1 Comment

@max2020 to explain this, your code wasn't working because the it was always trying to set the CSS property "cssProperty", rather than using the actual value of the variable cssProperty.
1

You need to build your object separately if you're in an environment that supports ES6 computed property names.

function addCss(element, cssProperty, cssValue) {
   var rule = {};
   rule[cssProperty] = cssValue;
   $(element).css(rule); 
}

Comments

Your Answer

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