Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML DOM Modify HTML Content

HTML DOM - Modify HTML Content


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


Change HTML Content

The easiest way to change the content of an element is to use the innerHTML property.

The following example changes the

element's HTML content:

Example

<p id="p1">

Hello World!

p

<

script

document.getElementById("p1").innerHTML="new text!";

script

<

p

The paragraph content is modified by a script.

p

Try it »


Change HTML Style

Through the HTML DOM, you can access the style object of HTML objects.

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

Try it »


Use Events

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

When something happens to an HTML element, the browser generates an event:

You can learn more about events in the next chapter.

The two examples below change the element's background color when a button is clicked:

Example

<input type="button" onclick=">

document.body.style.backgroundColor='lavender';

"

value

=

"

Modify Background Color

"

Try it »

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

Modify Background Color

"

/>

Try it »

The following example changes the

element's text:

Example

<p id="p1">

Hello world!

p

<

script

function ChangeText() { document.getElementById("p1").innerHTML="Hello Runoob!"; }

script

<input type="button" onclick="ChangeText()" value=">

Modify Text

"

/>

Try it »