You can use the method setProperty
, available in the object Element.style
. For example:
const body = document.querySelector('body');
function changeCSS() {
const propName = 'background-color';
const propValue = 'blue';
body.style.setProperty(propName, propValue);
}
<button onclick="changeCSS();">Mudar CSS</button>
Read Access Javascript properties: point notation or square brackets? to understand why the question code did not work. In short, the point notation does not work dynamically.
Therefore, as the linked answer points out, another option for this type of situation is to use, instead of the point, bracket notation - which accepts "dynamic" strings as property keys.
But note that in this case you will have to use the name of the property in its format camelCase
instead of dash-case
, wow that the object Element.style
has CSS properties following convention camelCase
. So instead of "background-color"
, you would have the key "backgroundColor"
.
Analogous to the example above, it looks like this:
const body = document.querySelector('body');
function changeCSS() {
// Note que o nome agora foi escrito em camelCase:
const propName = 'backgroundColor';
const propValue = 'blue';
body.style[propName] = propValue;
}
<button onclick="changeCSS();">Mudar CSS</button>
It is ideal to make a check if the name of the property is valid before making this last type of definition. But I omitted this part for brevity.
id
is not a reserved string? think you cannot use it as a name of. variable...– hugocsl
@hugocsl,
id
is valid. It is not part of the list of reserved words javascript.– Luiz Felipe
You are trying to set a CSS property
nome
that does not exist. It would need to beid.style[nome]
. OBS: the variable ofid
is misnamed, it does not contain an element’s ID, but the element itself.– bfavaretto
@Luizfelipe Pasta! I thought I could be, but I wasn’t sure. Thanks for the tip!
– hugocsl