JavaScript HTML DOM - Changing CSS
The HTML DOM allows JavaScript to change the style of HTML elements.
Changing HTML Style
To change the style of an HTML element, use this syntax:
The following example changes the style of a <p>
element:
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</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>
Using Events
The HTML DOM allows us to execute code by triggering events.
For example, the following events:
An element is clicked.
The page has finished loading.
An input field is changed.
...
In the next sections, you will learn more about events.
This example changes the style of the HTML element with id="id1" when the user clicks the button:
Example
<!DOCTYPE html><html><body><h1 id="id1">My Header 1</h1>
<button type="button" onclick="document.getElementById('id1').style.color='red'">
Click Me!</button></body></html>