HTML DOM - Modify HTML content
Through the HTML DOM, JavaScript can access every element in the HTML document.
Changing 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 <p> element:
Example
<html><!DOCTYPE html> <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="New text!"; </script> <p>The paragraph above was changed by a script.</p> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
Change HTML styles
Through the HTML DOM, you can access the style object of the HTML object.
The following example changes the HTML style of a paragraph:
Example
<html><!DOCTYPE html> <html> <body> <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> </body> </html>
Run Example»
Click the "Run Instance" button to view an online instance
Using Events
The HTML DOM allows you to execute code when events occur.
When "something happens" to an HTML element, the browser generates an event:
Click on the element
Loading page
Changing input fields
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
<html><!DOCTYPE html> <html> <body> <input type="button" onclick="document.body.style.backgroundColor='lavender';" value="Change background color"> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
In this example, the same code is executed by the function:
Example
<html><!DOCTYPE html> <html> <body> <script> function ChangeBackground() { document.body.style.backgroundColor="lavender"; } </script> <input type="button" onclick="ChangeBackground()" value="Change background color" /> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance
The example below appears when the button is clicked When changing the text of the <p> element:
Instance
<html><!DOCTYPE html> <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>
Run Instance»
Click "Run Instance" Button to view online examples