0

I want to enter the value of the property in the entry field, for example color.

And In the other entry field for the new style is blue

let p_change = document.getElementById('p-change');
let property = document.getElementById('property').value; // each color ,fontSize
let newStyle = document.getElementById('style').value;  // each  red , 20px
let change  = document.getElementById('change');

change.onclick = function(){
 p_change.style.property = 'newStyle'; 
}
<p id="p-change">Change my style like you love</p>
      <input id="property" value="" placeholder="Enter Property">
    <input id="style" value="" placeholder="Enter New Style">
      <button id="change">Change</button>
enter image description here
  • Does this answer your question? [How to change css property using javascript](https://stackoverflow.com/questions/15241915/how-to-change-css-property-using-javascript) – Telmo Dias Mar 03 '20 at 12:04

2 Answers2

0

You need to get the property and the styles after you click the button.

If you get them before, they are empty strings.

Also, use const not let. No need to use let in this case.

Also added a small verification the see if the property entered exists or not.

const p_change = document.getElementById('p-change');
const change = document.getElementById('change');

change.onclick = function() {
  const property = document.getElementById('property').value
  const newStyle = document.getElementById('style').value;

  // extra verification
  const style = p_change.style
  const findPropertyArr = Object.keys(style).filter(key => key === property)
  if (findPropertyArr.length > 0) {
    p_change.style[`${property}`] = `${newStyle}`;
    document.getElementById('error').remove();
  } else {
    p_change.innerHTML += '<p id="error" style="color:red">Invalid property name</span>'
  }
}
<p id="p-change">Change my style like you love</p>
      <input id="property" value="" placeholder="Enter Property">
    <input id="style" value="" placeholder="Enter New Style">
      <button id="change">Change</button>
Mihai T
  • 17,254
  • 2
  • 23
  • 32
  • it works with let. But let has other use cases. You basically use `let` when you will change the value of that variable. For eg `let errorMessage = ' Some error ' ` and then further down in your code `if (a> b) { errorMessage = ' Different error ' } ` – Mihai T Mar 03 '20 at 12:39
-1

selected nodes has style property with css properties in it.

let node = document.querySelector('#someid')
node.style.color = 'red'
node.style.fontSize = '40px'
Sugar
  • 490
  • 9
  • 22