How to change css styles of elements in JavaScript?


JavaScript can change Css styles such as color, font size etc. of elements using some methods such as getElementById(), getElementByClassName() etc.

In the following example font style and font size of the elements have changed using getElementById() method.

Example-1

Live Demo

In the following example, using style commands "style.fontSize" and "style.fontStyle", the provided texts are changed to a font size of "35px" and font style to "italic"

<html>
<body>
   <p id="size">JavaScript can change the style of an HTML element.</p>
   <p id="style">JavaScript can change the style of an HTML element.</p>
   <button type="button"
   onclick="document.getElementById('size').style.fontSize='35px'">Size</button>
   <button type="button" onclick="document.getElementById('style')
.style.fontStyle='italic'">Style</button>
</body>
</html>

On executing the above code we will get the following on the browser.

After clicking the above buttons first text will be changed to different font size and second text will be changed to a different font style as shown in the output.

Output

Example-2

In the following example the color of the text has changed to blue using style command "style.color".

Live Demo

<html>
<body>
   <p id="color">JavaScript can change the color of an HTML element.</p>
   <button type="button" onclick="document.getElementById('color').
   style.color='blue'">Color Me</button>
</body>
</html>

After executing above code we will get the following on the browser window. 

On clicking on the "color me" button the provided text's color will be changed to 'blue' as shown in the output.

Output

  

Updated on: 29-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements