Easy Tutorial
❮ Index Htmldom Summary ❯

HTML DOM - Modifying HTML Content


Through the HTML DOM, JavaScript can access every element in an HTML document.


Changing HTML Content

The simplest way to change the content of an element is by using the innerHTML property.

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

Example

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

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

<p>The paragraph content is modified by script.</p>

Changing HTML Styles

Using the HTML DOM, you can access the style object of an HTML object.

The following example changes the HTML style of a paragraph:

Example

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

Using Events

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

Events are generated by the browser when "something happens" to HTML elements:

You can learn more about events in the next chapter.

The following two examples change the background color of the <body> element when a button is clicked:

Example

<input type="button"
onclick="document.body.style.backgroundColor='lavender';"
value="Change background color">

In this example, the same code is executed by a function:

Example

<script>
function ChangeBackground() {
    document.body.style.backgroundColor = "lavender";
}
</script>

<input type="button" onclick="ChangeBackground()" value="Change background color" />

The following example changes the text of a <p> element when a button is clicked:

Example

<p id="p1">Hello world!</p>

<script>
function ChangeText() {
    document.getElementById("p1").innerHTML = "Hello tutorialpro!";
}
</script>

<input type="button" onclick="ChangeText()" value="Change text" />
❮ Index Htmldom Summary ❯