JavaScript DOM CSS
JavaScript Basics

JavaScript DOM CSS

JavaScript HTML DOM - Changing CSS

The HTML DOM allows JavaScript to modify the style of HTML elements.

Changing HTML Style

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

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

Example: Changing Text Color

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

<!DOCTYPE html><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 triggered by the browser when actions happen to HTML elements, such as:

  • An element being clicked
  • The page loading
  • Input fields being changed

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

Example: Changing Style on Click

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

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

Visibility

You can control the visibility of an element to make it visible or invisible.

HTML DOM Style Object Reference

For a comprehensive list of all HTML DOM style properties, refer to our complete HTML DOM Style Object Reference.

Test Yourself With Exercises

Exercise:

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

<p id="demo">
Some text</p>‍
<script>document.getElementById("demo").style.color = "red";

</script>‍

Take a look into your desired course