Latest web development tutorials

HTML DOM Edit HTML content

Through the HTML DOM, JavaScript can access the HTML document for each element.


Change the HTML content

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

The following example changes <p> element in HTML content:

Examples

<html>
<body>

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

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

</body>
</html>

try it"


Change HTML styles

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

The following example changes the HTML paragraph styles:

Examples

<html>

<body>

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

<script>
document.getElementById("p2").style.color="blue";
</script>

</body>
</html>


try it"


Use Event

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

When the HTML element "something is happening", the browser will generate an event:

  • Click on an element
  • Loading page
  • Change the input field

You can learn more about the event in the next chapter.

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

Examples

<html>
<body>

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

</body>
</html>

try it"

In this case, the function performs the same code:

Examples

<html>
<body>

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

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

</body>
</html>

try it"

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

Examples

<html>
<body>

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

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

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

</body>
</html>

try it"