JavaScript HTML DOM - Change CSS
HTML DOM allows JavaScript to change the style of HTML elements.
Change HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=New style
The example below changes the style of a <p> element:
Examples
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example (example.com)</title>
</head>
<body>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>
<p>The paragraph above was modified by a script.</p>
</body>
</html>
Try it yourself »
Using Events
HTML DOM allows us to execute code when events are triggered.
For example, the following events:
- An element is clicked.
- The page finishes loading.
- An input field is modified.
- ……
In the following chapters, you will learn more about events.
This example changes the style of the HTML element with id="id1" when the user clicks the button:
Examples
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click me!</button>
</body>
</html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click me!</button>
</body>
</html>
Try it yourself »
More Examples
Visibility
How to make an element invisible. Do you want the element to show or disappear?