Heapcoding

How to change CSS property using Javascript

Published July 29, 2021

How to change CSS property using Javascript

You can do many things in pure CSS language. But sometimes you need to change some CSS properties using Javascript language as well.

In this tutorial I shall guide you step by step on how to change CSS property using Javascript.

Step 1 – Create basic html document

How to change CSS property using Javascript

In the above screenshot you will see the basic HTML5 document. 

  1. Where I have HTML5 declaration at line #1
  2. HTML root element at line #02
  3. Head tag at line #03
  4. And body tag at line #05

Step 2 – Add a paragraph tag and text

Add a paragraph tag and text

In the above screenshot you will see I have added a paragraph with some text. Now let’s use Javascript to change the color of the paragraph with CSS.

Step 3 – Get paragraph element in Javascript using ID

Get paragraph element in Javascript using ID

In the above screenshot, on line #06 you will see I have added an id attribute with the value “my-paragraph”.

And I have added a script tag in our document to write the Javascript code. And in the script tag I have created a “_p” variable where I have got the paragraph element by id.

And finally on line #09 I have added a console.log method to show you the element that I have got by rendering in the web browser.

Let’s render the webpage and see the element which we got in the browser console tab.

How to change CSS property using Javascript

In the above screenshot you can see the rendered text on screen and when you press “CTRL+SHIFT+i” on windows the developer tools tab will be opened. 

From there select the console tab and you will see a paragraph element printed in console window, as above red bordered text in picture.

Step 3 – Let’s add more javascript to change CSS property

Let’s add more javascript to change CSS property

In the above screenshot on line #09 you can see I have manipulated the color property from the style object of the paragraph element in Javascript. This will change the color of the paragraph to red.

Let’s render this code in our web browser to see the changes.

How to change CSS property using Javascript

In the above screenshot you will see that our paragraph text is now red. And from developers tools, click on the “Elements” tab and you will see an inline style attribute added with the property “color” and value “red”.

When you manipulate an element’s CSS via Javascript that always adds inline CSS.

So this was the simple method to change the CSS property of an element using Javascript.

You may also like: