- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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".
<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