简体   繁体   中英

How to change style in javascript using a variable?

I want to prompt the user for a CSS property and a value and change the style of the paragraphs but I can't get the property working

function change()
  var prop = prompt("Enter a css property");
  var val = prompt("Enter a value for the property");
  var x = document.querySelectorAll("p");
  for (i = 0; i < x.length; i++) {
    x[i].style.prop = val;
  }
}

You're trying to set the style prop , not the variable that's inside prop . Use brackets to signify prop is a variable, and to use the value contained inside of it:

x[i].style[prop] = val;

Here is a working demo:

 function change() { var prop = 'color'; var val = 'blue'; var x = document.querySelectorAll("p"); for (i = 0; i < x.length; i++) { x[i].style[prop] = val; } } 
 <p>Will turn blue</p> <button onclick="change()">Turn paragraphs blue</button> 

Try This Code

 function change(){ var prop = prompt("Enter a css property"); var val = prompt("Enter a value for the property"); var x = document.querySelectorAll("p"); for (var i = 0; i < x.length; i++) { x[i].style[prop] = val; } } 
 <html> <head> </head> <body> <button onclick="change()">Change Style</button> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM