Reputation: 44842
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
Upvotes: 0
Views: 714
Reputation: 120516
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"
Upvotes: 3
Reputation: 1805
If you don't mind using a framework, have a look at jQuery, especially this: http://api.jquery.com/css/
Upvotes: 0
Reputation: 8826
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
Upvotes: 0