How to define a dynamic named CSS property via Javascript?

Asked

Viewed 71 times

4

I need to use the value of a string to change a CSS property of an element.

I tried to do this, but it didn’t work:

function funciona(nome, valor, id){
  id.style.nome = valor;
}

function changecolor(){
  var id = document.getElementById('teste');
  var nomeProp = "background-color";
  var valorprop = "green";
  funciona(nomeProp, valorprop, id);
}
<h1 style="cursor:pointer; color:pink;" onclick="changecolor();"> este é um teste </h1>
<div id="teste" style="background-color:red; width:200px; height:170px;"> </div>

  • id is not a reserved string? think you cannot use it as a name of. variable...

  • @hugocsl, id is valid. It is not part of the list of reserved words javascript.

  • 2

    You are trying to set a CSS property nome that does not exist. It would need to be id.style[nome]. OBS: the variable of id is misnamed, it does not contain an element’s ID, but the element itself.

  • @Luizfelipe Pasta! I thought I could be, but I wasn’t sure. Thanks for the tip!

2 answers

6


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.

1

If it is just a type of property, you can use the style attribute itself, which contains all CSS values, both for query and for change:

const color = "blue";
element.style.backgroundColor = color;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.