JavaScript HTML DOM - Change HTML
- Previous Page DOM Elements
- Next Page DOM Forms
HTML DOM allows JavaScript to change the content of HTML elements.
Change HTML output stream
JavaScript can create dynamic HTML content:
In JavaScript,document.write()
It can be used to directly write to the HTML output stream:
Example
<!DOCTYPE html> <html> <body> <script> document.write(Date()); </script> </body> </html>
Never use document.write() after the document has been loaded document.write()
. This will overwrite the document.
Change HTML content
The simplest way to change HTML content is to use innerHTML
property.
To modify the content of an HTML element, please use this syntax:
document.getElementById(id).innerHTML = new text
This example modifies <p>
Content of the element:
Example
<html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "hello kitty!"; </script> </body> </html>
Example Explanation:
- The above HTML document contains a <p> element with id="p1"
- We use the HTML DOM to retrieve this element with id="p1"
- JavaScript changes the content (innerHTML) of the element to "Hello Kitty!"
This example modifies <h1>
Content of the element:
Example
<!DOCTYPE html> <html> <body> <h1 id="header">Old Header</h1> <script> var element = document.getElementById("header"); element.innerHTML = "New Header"; </script> </body> </html>
Example Explanation:
- The above HTML contains a <h1> element with id="header"
- We used the HTML DOM to retrieve the element with id="header"
- JavaScript changes the content of this element (innerHTML)
Change the value of the attribute
To change the value of an HTML attribute, use the following syntax:
document.getElementById(id).attribute = new value
This example modifies <img>
of the element src
Value of the attribute:
Example
<!DOCTYPE html> <html> <body> <img id='myImage' src='smiley.gif'> <script> document.getElementById('myImage').src = 'landscape.jpg'; </script> </body> </html>
Example Explanation:
- The above HTML document contains an <img> element with id='myImage'
- We use HTML DOM to get the element with id='myImage'
- JavaScript changes this element's src attribute from 'smiley.gif' to 'landscape.jpg'
- Previous Page DOM Elements
- Next Page DOM Forms