Chapter 8: DOM element Properties

8.1 Changing CSS styles

First, let’s look at how we can use Javascript to change the CSS style of an element. To do that, we use the style property.

This property uses a similar naming convention to CSS. The main difference is, instead of using hyphens when the property name is made up of two or more words, we use camel casing.

For instance, suppose we want to change the background and font color of an element.

To do that in CSS, we write

#first {
    color: red;
    background-color: yellow;
}

To do that in Javascript, we write

document.getElementById("first").style.color = "Red";
document.getElementById("first").style.backgroundColor = "Yellow";

We first select the element using

document.getElementById("first")

Next, we use the

style.color

and

style.backgroundColor

properties to change the font and background color respectively.

Javascript style property

Try adding the two Javascript statements above to chap8.js to see them at work. You’ll see the text color of the first line change to red and the background color change to yellow.

Note that CSS code added using the style property is considered inline CSS. Hence, it has higher precedence compared to code added by embedding or linking.

For instance, if you add the following lines to DOMProperties.html (before the </head> tag),

<style>
#first {
    color: green;
    background-color: pink;
    text-decoration: underline;
}
</style>

you’ll see that while the first line gets underlined, the font and background color are not changed. This is because the two Javascript statements we added previously have higher precedence than the CSS code above.