WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript HTML DOM - Changing CSS


The HTML DOM permits JavaScript to change the style of HTML elements.


Changing HTML Style

To change the style of an HTML element, use this syntax:

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

The following example will change <p> Element style´╝Ü

Example

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The passage above was changed by a script.</p>

</body>
</html>
Try it Yourself »

Using Events

The HTML DOM allows us to execute code by triggering events.

For example, the following event:

  • The element was clicked.
  • Page loading is complete.
  • The input box has been 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 Heading 1</h1>

<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Snap Me!</button>

</body>
</html>
Try it Yourself »

More Examples

Visibility Step by step instructions to make a component imperceptible. Would you like to demonstrate the component or not?


HTML DOM Style Object Reference

For all HTML DOM style properties, take a gander at our total HTML DOM Style Object Reference.