HTML DOM - Chaning 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 attribute.

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

Example

<p id="p1">Hello World!</p>
 
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
 
<p> paragraphs are scripted to modify the content. </p>

Try It! 


Change HTML Style

With the HTML DOM, you can access the style objects 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 Event

HTML DOM allows you to execute code when events occur.

The browser generates events when "something happens" to an HTML element:

  • Click on element

  • Load page

  • Change input field

You can learn more about events in the next chapter.

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

Example

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

Try It! 

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

Example

<script>
function ChangeBackground()
{
    document.body.style.backgroundColor="lavender";
}
</script>
 
<input type="button" onclick="ChangeBackground()" value="Change background color" />

Try It! 

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

Example

<p id="p1">Hello world!</p>
 
<script>
function ChangeText()
{
    document.getElementById("p1").innerHTML="Hello Tutorialfish.com!";
}
</script>
 
<input type="button" onclick="ChangeText()" value="Change text" />

 Try It!