Search code examples
javascripthtmlcssinline-styles

Changing inline CSS using JavaScript isn't working


I'm trying to change the width of an element using JavaScript.

This doesn't throw any error. It instead silently ignores the code.

pageSettings = {
  'padding': 16    
}
document.querySelector('#container').style.setProperty(
  'width',
  `calc(100vw - (20em + ${pageSettings['padding'] * 2}px)) !important;`
)
<div class='container' id='container'>
  <p>Content</p>
</div>


Solution

  • If needed your important should be the 3rd parameter of setProperty

    But take a look at When to use the !important property in CSS

    const pageSettings = { 'padding': 16 },
      container = document.querySelector('#container');
    
    console.log(getComputedStyle(container).width); // before 
    
    setTimeout(() => {
      container.style.setProperty(
        'width',
        `calc(100vw - (20em + ${pageSettings['padding'] * 2}px))`,
        'important')
    
      console.log(getComputedStyle(container).width); // after
    
    }, 2000)
    .container {
      border: 1px solid black;
      width: 60px;
      text-align:center;
    }
    <div class='container' id='container'>
      <p>Content</p>
    </div>