JavaScript style Property Tutorial

In this section, we will learn what the Element style property is and how to use it in JavaScript.

What is Element style Property in JavaScript?

The JavaScript Element style property is used to get or set the CSS properties of an element.

Basically, the style property returns an object called CSSStyleDeclaration that contains the entire CSS properties. So using these properties, we can easily either get or set the CSS properties of an element and hence style it.

You should know that in some cases the properties used in the CSSStyleDeclaration object are a bit different from their relatives used in CSS.

For example, in CSS we have a property called `background-color` that is used to change the background color of an element. But in CSSStyleDeclaration object, this property is represented as `backgroundColor`. As you can see, instead of using a dash `-` those properties that have more than just one name, are camelCased!

Just to give you another example: font-size in CSS is equal to fontSize in CSSStyleDeclaration object.

JavaScript style Property Syntax:;

JavaScript style Property Input Value

The style property is read-only and so we can’t assign a value to it.

JavaScript style Property Return Value

The return value of the style property is a reference to the CSSStyleDeclaration property that contains the CSS properties as its own properties. So, using this object, we can style an element.

Example: JavaScript add style to element

See the Pen JavaScript add style to element by Omid Dehghan (@odchan1) on CodePen.

Example: styling with JavaScript

See the Pen styling with JavaScript by Omid Dehghan (@odchan1) on CodePen.

Example: set style in JavaScript

See the Pen set style in JavaScript by Omid Dehghan (@odchan1) on CodePen.


Top Technologies