JavaScript HTML DOM - Changing CSS
The 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 following example changes the
element's style:
Example
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>Runoob Tutorial(runoob.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 above paragraph is modified by the script.
p
body
html
Try it »
Use Events
The HTML DOM allows us to execute code by triggering events.
Such as 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: