rye Guy
rye Guy

Reputation: 33

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;
  }
}

Upvotes: 1

Views: 94

Answers (2)

sarbudeen
sarbudeen

Reputation: 170

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>

Upvotes: 0

Blue
Blue

Reputation: 22911

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>

Upvotes: 2

Related Questions