Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

DOM CSS

The HTML DOM enables JavaScript to modify the styles of HTML elements.

Changing HTML Style

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

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

The following example modifies 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 enables you to execute code in response to events.

Events are triggered by the browser when certain actions occur on HTML elements, such as:

  • Clicking on an element
  • The page finishing loading
  • Changes to input fields

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>