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 a HTML component, utilize this syntax:

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

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



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

document.getElementById("p2").style.color = "blue";

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

Try it Yourself »

Using Events

The HTML DOM enables you to execute code when an occasion occurs.

Events are created by the program when "things happen" to HTML elements:

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

You will get familiar with occasions in the following section of this tutorial.

This model changes the style of the HTML component with id="id1", when the client clicks a button:


<!DOCTYPE html>

<h1 id="id1">My Heading 1</h1>

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

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.

Test Yourself with Exercises!

Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »