Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

HTML DOM modifies HTML content


May 09, 2021 HTML DOM


Table of contents


HTML DOM - Modify HTML content


With HTML DOM, JavaScript has access to every element in an HTML document.


Change the HTML content

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

The following example changes the HTML content of the element:

<html>
<body>

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

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

</body>
</html>

Try it out . . .


Change the HTML style

HTML DOM allows you to access style objects for HTML objects.

The following example changes the HTML style of a paragraph:

<html>

<body>

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

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

</body>
</html>


Try it out . . .


Use events

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

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

  • Click on the element
  • Load the page
  • Change the input field

You can learn more about events in the next chapter.

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

<html>
<body>

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

</body>
</html>

Try it out . . .

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

<html>
<body>

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

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

</body>
</html>

Try it out . . .

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

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


These 5 examples can help you better understand how to modify HTML content, and we recommend that you take a closer look and get started before you learn about the HTML DOM elements in the next chapter