JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

Just as you can use JavaScript to change the HTML in a web page, you can also use it to change CSS styles. The process is very similar.

The first step is to select the element you want to apply or change a style on. For example, to select a robot's left eye, you can use the following code:

document.getElementById("lefteye")

After you've selected an element, you can change its style by attaching the style property to the selector, followed by the style you want to change. To change the color of the left eye, you can use this JavaScript:

document.getElementById("lefteye").style.backgroundColor = "purple";

Do you notice anything strange about this code? When changing styles with JavaScript, there are two rules:

  • When the CSS property is just one word, such as margin or border, you can use the same CSS name to change the style in JavaScript.

  • If the CSS property has dashes (), the CSS property name gets converted to camelCase. So, backgroundcolor gets changed to backgroundColor.

Here are some examples of CSS properties, and how each property is spelled in JavaScript:

CSS Property JavaScript Style Property
background‐color backgroundColor
border‐radius borderRadius
font‐family fontFamily
margin margin
font‐size fontSize
border‐width borderWidth
text‐align textAlign
color color

JavaScript cares a lot about capitalization. The capital letters in the JavaScript style properties need to be there in order for the properties to work.

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: