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?


Use element.style:

var element = document.createElement('select');
element.style.width = "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");

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"

That's actually quite simple with vanilla JavaScript:

menu.style.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')