DOM CSS


JavaScript HTML DOM-change CSS


HTML DOM allows JavaScript to change the style of HTML elements.


Change HTML style

To change the style of HTML elements, use this syntax:

document.getElementById(id).style.property = New style    

The following example will change the style of the <p> element:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TutorialFish Tutorial (tutorialfish.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 paragraphs are modified through scripts. </p>
 
</body>
</html>

Try It! 


Use event

HTML DOM allows us to execute code by triggering events.

For example, the following events:

  • The element is clicked.

  • The page is loaded.

  • The input box 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:

Example

<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My headline 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click me!</button>

</body>
</html>

 Try It! 



More examples

How Visibility makes the element invisible. Do you want the element to show up or disappear?