What is the style property in DOM?

Overview

In this shot, we will learn how to get or change the style of any HTML element using the style property.

The common way to give HTML pages style is through CSS, but we will change the style using the property while HTML is running.

element.style will return a CSS style declaration object. Using this object, we can set any CSS property. For example, to set the color we can write: element.style.color = red. If nothing is assigned to the property, it will return the default CSS values.

Code

Let’s try to change the style of the div element.

Explanation

  • In line 5, we have a div element with text and an id = elem.

  • In line 7, we have a paragraph tag for displaying text.

  • In line 9, we have written a button tag with a function change(). The function will be called when the user clicks on this button tag.

  • In line 12, we have written the JavaScript code in the script tag. We have defined a function change(), which will be called when the user clicks on the HTML page button.

  • In line 13, inside the function change(), we will get the div element by using document.getElementById() and passing elem into it. Then, we will apply the style property, which will return a CSS style declaration object.

  • In line 14, we will set the CSS color property to red. We can also try this with a different style property.

Output

When we click the button, the style of the div changes and the text color turns from black to red. We can set any other CSS property, using the style property. We can also get the style value with element.style.property, which will return the CSS value it has for that property.

Free Resources