1

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

2 Answers 2

2

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>

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

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.