Reputation: 33
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
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
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