JavaScript Kit > JavaScript Reference > Here
Style Object
The Style object of the DOM allows you to dynamically change the values of your CSS properties, whether defined inline or via an external style sheet. The changes are instantly reflected on the page. The syntax is:
Inline Style:
element.style.color="red" //change element to red by modifying its CSS "color" property.
External Style:
//In Firefox, change the color property of the first rule
of the first external CSS on page:
document.styleSheets[0].cssRules[0].style.color="red"
//In IE Win, change the color property of the first rule
of the first external CSS on page:
document.styleSheets[0].rules[0].style.color="red"
Example 1:
<a id="mylink" href="http://www.dynamicdrive.com">Dynamic Drive</a>
<script type="text/javascript">
document.getElementById("mylink").style.color="red"
</script>
Example 2:
<div style="background-color:white; width:100px; height:100px" onMouseover="this.style.backgroundColor='#E2E2E2'" onMouseout="this.style.backgroundColor='white'">This is a div</div>
Notice in Example 2 the use of "backgroundColor" as the scripting equivalent of "background-color" in CSS. In JavaScript, to access a CSS property that contains hyphens (ie: background-color), drop the hyphen and instead capitalize the first letter following it.
Example 3:
<style type="text/css">
p{
font-size: 16px;
}
</style>
<script type="text/javascript">
var firstsheet=document.styleSheets[0]
var therules=firstsheet.cssRules? firstsheet.cssRules: firstsheet.rules
therules[0].style.backgroundColor="yellow"
</script>
Note: See our CSS Reference for a comprehensive list of CSS attributes.
Properties
Properties | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Most CSS attributes are represented as
properties in the Style object. For non hyphenated attributes, the
property is identical, while for hyphenated attributes, drop the
hyphen and capitalize the first letter following it. For instance,
to manipulate the "background-color" property of CSS via the DOM,
the syntax would look something like: document.getElementById("george").style.backgroundColor="white" Examples:
See our CSS Reference for a comprehensive list of CSS attributes. |
- JavaScript Operators
- JavaScript Statements
- Global functions
- JavaScript Events
- Escape Sequences
- Reserved Words