I'm wondering how would I change a CSS element in javascript..e.g if a user clicks a button it changed the background from white to black
-
3Duplicate: http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript – Mikhail Feb 04 '11 at 17:28
5 Answers
Every DOM element has a style
property that allows manipulation of CSS properties on that object as if you were mucking with it's style
attribute.
The below will toggle the color of the document body but is equally applicable to other HTML elements.
<button onclick="document.body.style.background = (toggle = !toggle) ? 'black' : 'white'">Toggle Background</button>
As TheBuzzSaw points out, you need to camel case them.
So the JS property is backgroundColor
instead of background-color
.
The rule is basically
var javascriptProperty = cssStyleProperty.replace(
/-([a-z])/g,
function (_, followingLetter) { return followingLetter.toUpperCase(); });
but there are a few exceptions : since float
is a keyword in many languages, the CSS style property is cssFloat
. The exceptions are explained under JavaScript syntax in the w3schools pages : http://www.w3schools.com/css/pr_class_float.asp
JavaScript syntax: object
.style.cssFloat="left"

- 118,113
- 30
- 216
- 245
There are many properties/attributes that can be manipulated directly from JavaScript. You just need to know their names. They are usually strange camel case equivalents of the CSS property names. A quick Google search reveals lots of places to learn about this.
http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html

- 8,648
- 5
- 39
- 58
load new image with black color on click event of the button

- 459
- 1
- 6
- 14
-
This is a simple way...but go for attributes for programing perspective :) – Chirag Tayal Feb 04 '11 at 17:31
If you don't mind using a framework, have a look at jQuery, especially this: http://api.jquery.com/css/

- 1,805
- 2
- 17
- 23