[javascript] Set CSS property in Javascript?

I've created the following...

var menu = document.createElement('select');

How would I now set CSS attributes e.g width: 100px?

This question is related to javascript css

The answer is


It is important to understand that the code bellow does not change the stylesheet, but instead changes the DOM:

document.getElementById("p2").style.color = "blue";

The DOM stores a computed value of the stylesheet element properties, and when you dynamically change an elements style using Javascript you are changing the DOM. This is important to note, and understand because the way you write your code can affect your dynamics. If you try to obtain values that were not written directly into the element itself, like so...

let elem = document.getElementById('some-element');
let propertyValue = elem.style['some-property'];

...you will return an undefined value that will be stored in the code example's 'propertyValue' variable. If you are working with getting and setting properties that were written inside a CSS style-sheet and you want a SINGLE FUNCTION that gets, as well as sets style-property-values in this situation, which is a very common situation to be in, then you have got to use JQuery.

$(selector).css(property,value)

The only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery. If you want to get a CSS property that was computed from a style-sheet in pure JavaScript then you need to use.

function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

The downside to this method is that the getComputedValue method only gets, it does not set. Mozilla's Take on Computed Values This link goes more into depth about what I have addressed here. Hope This Helps Someone!!!


That's actually quite simple with vanilla JavaScript:

menu.style.width = "100px";

<h1>Silence and Smile</h1>
<input  type="button"  value="Show Red"   onclick="document.getElementById('h1').style.color='Red'"/>
<input  type="button"  value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>

<body>
  <h1 id="h1">Silence and Smile</h1><br />
  <h3 id="h3">Silence and Smile</h3>

  <script type="text/javascript">
    document.getElementById("h1").style.color = "Red";
    document.getElementById("h1").style.background = "Green";
    document.getElementById("h3").style.fontSize = "larger" ; 
    document.getElementById("h3").style.fontFamily = "Arial";
  </script>
</body>

This works well with most CSS properties if there are no hyphens in them.

var element = document.createElement('select');
element.style.width = "100px";

For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase

var element = document.createElement('select');
element.style.maxWidth = "100px";

if you want to add a global property, you can use:

    var styleEl = document.createElement('style'), styleSheet;
            document.head.appendChild(styleEl);
            styleSheet = styleEl.sheet;
            styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);

When debugging, I like to be able to add a bunch of css attributes in one line:

menu.style.cssText = 'width: 100px';

Getting used to this style you can add a bunch of css in one line like so:

menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';

For most styles do this:

var obj = document.createElement('select');
obj.style.width= "100px";

For styles that have hyphens in the name do this instead:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"

Just set the style:

var menu = document.createElement("select");
menu.style.width = "100px";

Or if you like, you can use jQuery:

$(menu).css("width", "100px");

All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.

Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.

In prototype I would do:

$(newElement).addClassName('blah')

Just for people who want to do the same thing in 2018

You can assign a CSS custom property to your element (through CSS or JS) and change it:

Assigment through CSS:

element {
  --element-width: 300px;

  width: var(--element-width, 100%);
}

Assignment through JS

ELEMENT.style.setProperty('--element-width', NEW_VALUE);

Get property value through JS

ELEMENT.style.getPropertyValue('--element-width');

Here useful links: