Categories:

JavaScript Kit > DOM Reference > Here

DOM inline "style" object

Last updated: Februrary 27th, 2006

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 it's CSS color property.

External Style:

//In Firefox, change the color property within 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 within 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:

Attribute Property of the Style Object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth

See our CSS Reference for a comprehensive list of CSS attributes.

Sponsored By

DD CSS Library
Free CSS menus and codes to give your site a visual boost.

DOM Window
DOM Document
DOM Element
DOM Event
DOM Style
DOM Table
Miscellaneous

 

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info