DOM HTML
JavaScript HTML DOM - Change HTML
HTML DOM allows JavaScript to change the content of HTML elements.
Change the HTML output stream
JavaScript can create dynamic HTML content:
Today's date is:
In JavaScript, document.write() can be used to write content directly to the HTML output stream.
Example
<!DOCTYPE html> <html> <body> <script> document.write(Date()); </script> </body> </html>
![]() | Never use document.write() after the document (DOM) has been loaded. This will overwrite the document. |
---|
Change HTML content
The easiest way to modify HTML content is to use the innerHTML attribute.
To change the content of HTML elements, use this syntax:
document.getElementById(id).innerHTML = New HTML
This example changes the content of the <p> element:
Example
<html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="New text!"; </script> </body> </html>
This example changes the content of the <h1> element:
Example
<!DOCTYPE html> <html> <body> <h1 id="header">Old Header</h1> <script> var element=document.getElementById("header"); element.innerHTML="New title"; </script> </body> </html>
Example explanation:
The above HTML document contains the <h1> element with id="header"
We use HTML DOM to get the element with id="header"
JavaScript changes the content of this element (innerHTML)
Change HTML attributes
To change the attributes of HTML elements, use this syntax:
document.getElementById(id).attribute = New attribute value
This example changes the src attribute of the <img> element:
Example
<!DOCTYPE html> <html> <body> <img id="image" src="smiley.gif"> <script> document.getElementById("image").src="landscape.jpg"; </script> </body> </html>
Example explanation:
The above HTML document contains an <img> element with id="image"
We use HTML DOM to get the element with id="image"
JavaScript changes the attributes of this element (change "smiley.gif" to "landscape.jpg")