HTML DOM - Modifying HTML Content
With the HTML DOM, JavaScript can access every element in an
HTML document
Changing HTML Content
The easiest 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
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
Try it yourself »
Changing HTML Style
With the HTML DOM you can access the style object of HTML elements.
The following example changes the HTML style of a paragraph:
Example
<html>
<body>
<p id="p2">Hello world!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
</body>
</html>
Try it yourself »
Using Events
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
- An element is clicked on
- The page has loaded
- Input fields are changed
You can read more about events in the next chapter.
The following 2 examples changes the background color of the <body> element when a button is clicked:
Example
<html>
<body>
<input type="button" onclick="document.body.style.backgroundColor='lavender';"
value="Change background color" />
</body>
</html>
Try it yourself »
In this example the same code is executed by a function:
Example
<html>
<body>
<script>
function ChangeBackground()
{
document.body.style.backgroundColor="lavender";
}
</script>
<input type="button" onclick="ChangeBackground()"
value="Change background color" />
</body>
</html>
Try it yourself »
The following example changes the text of the <p> element when
a button is clicked:
Example
<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 yourself »
Thank You For Helping Us!
Your message has been sent to W3Schools.
Close [X]