JavaScript/Changing Element Styles

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Removing Elements Index Next: Event Handling

In order to change a style property of an element, change the value associated with the property under the "style" argument of the element. Let's continue with our button example from the last section:

<input type="button" id="myButton" value="I'm a button!">

Suppose we wish to hide the button with the display style property. In CSS, this would be done with:

#myButton { display: none; }

If the button should be initially visible, but we want to hide it later with JavaScript, this would be done with:

myButton = document.getElementById("myButton"); //searches for & detects input element of 'myButton' id
myButton.style.display = "none"; //hides the element

Hyphenated styles[edit]

Some style properties are hyphenated. In such cases, the associated JavaScript property has no hyphens, but the letters that appear after the hyphens are capitalized. (This is known as "camel case".)

For example, suppose we want the text of the button to be bold. In CSS, this would be done with:

#myButton { font-weight: bold; }

If the button should initially be normal, but we want to make its text bold later with JavaScript, this would be done with:

myButton = document.getElementById("myButton"); //searches for & detects input element of 'myButton' id
myButton.style.fontWeight = "bold"; //makes the text bold


Previous: Removing Elements Index Next: Event Handling