JavaScript HTML DOM - Change CSS

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 <p> Element Style:

Example

<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The above paragraph has been changed by the script.</p>
</body>
</html>

Try It Yourself

Using Events

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

When 'something' happens to an HTML element, the browser generates an event:

  • When an element is clicked
  • When the page is loaded
  • When the input field is changed

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

This example will change the style of the HTML element with id="id1" when the user clicks the button:

Example

<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Title 1</h1>
<button type="button" onclick="document.getElementById('id1').style.color = 'red'>
Click Me!
</button>
</body>
</html>

Try It Yourself

More Examples

Visibility
How to make an element invisible. Do you want to display the element?

HTML DOM Style Object Reference Manual

For all HTML DOM style properties, please visit our HTML DOM Style Object Reference Manual.