javascriptcssfunctionqueryselector

create fn for chenge CSS style in js


I need to create a function for changing the CSS Style like the below: (because I use this several times in my code)

document.querySelector('.number').style.width = '30rem';
document.querySelector('.number').style.color = 'green';
document.querySelector('body').style.backgroundColor = 'green';

can use like displayStyleNumber function:

const displayStyleNumber = (classElement, property, value) => {
  const displayCssStyle = `document.querySelector('${classElement}').style.${property} = '${value}';`
  return displayCssStyle;
}

when I use it, doesn't work!!! which part is wrong?


Solution

  • Did you mean?:

    const displayStyleNumber = (classElement, property, value) => {
      document.querySelector(classElement).style[property] = value;
    }
    <button id="btn" onclick="displayStyleNumber('#btn', 'backgroundColor', 'red')">click me</button>

    In your current form, the code creates a string and then returns it, it won't execute it

    Also, name of this function is misleading