Open In App

How to change style attribute of an element dynamically using JavaScript ?

Last Updated : 03 Aug, 2023
Comments
Improve
Suggest changes
3 Likes
Like
Report

Given an HTML document and the task is to change the style properties (CSS Properties) of an element dynamically with the help of JavaScript.

Approach: Using element.style Property

The element.style property is represented by the CSSStyleDeclaration object, which is returned via the style property.

  • Select the element whose style properties need to be changed.
  • Use element.style property to set the style attribute of an element.
  • Set the properties either by using bracket notation or dash notation.

Example 1: This example changes the color and background color of the heading element.

Output

How to change style attribute of an element dynamically using JavaScript ?
How to change style attribute of an element dynamically using JavaScript ?

Example 2: This example changes the color, background color, and width properties of elements. 

Output:

How to change style attribute of an element dynamically using JavaScript ?
How to change style attribute of an element dynamically using JavaScript ?

Similar Reads