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:

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

The following example changes the style of a <p> element:

Example

<html>
<body>

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

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

</body>
</html>

Using Events

The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when "things happen" to HTML elements:

  • An element is clicked on
  • The page has loaded
  • Input fields are changed

You will learn more about events in the next chapter of this tutorial.

This example changes the style of the HTML element with id="id1", when the user clicks a button:

Example

<!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>


More Examples

How to make an element invisible. Do you want to show the element or not?


HTML DOM Style Object Reference

For all HTML DOM style properties, look at our complete .


Test Yourself With Exercises

Exercise:

Change the text color of the <p> element to "red".

<p id="demo"></p>

<script>
document.getElementById("demo") = "red";
</script>



Login
ADS CODE