DOM CSS

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

DOM CSS

The HTML DOM enables 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

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM</h2>

<p>Changing the HTML style:</p>

<p id=”p1″>Hello World!</p>

<p id=”p2″>Hello World!</p>

<script>

document.getElementById(“p2”).style.color = “blue”;

document.getElementById(“p2”).style.fontFamily = “Arial”;

document.getElementById(“p2”).style.fontSize = “larger”;

</script>

</body>

</html>

Output

JavaScript HTML DOM

Changing the HTML style:

Hello World!

Hello World!

Using Events

The HTML DOM executes the 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.

This example is used to change 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>

Output

My Heading 1