JavaScript HTML DOM - Changing HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing 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
Try it »
![]() |
Never use document.write() after the document (DOM) has finished loading. It will overwrite the document. |
|---|
Change HTML Content
The simplest way to modify HTML content is to use the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(
id
).innerHTML=
New HTML
This example changes
element's content changes:
Example
Hello World!
Try it »
This example changes
element's content changes:
Example
Old Header
Try it »
Example explained:
- The HTML document above contains an element with id="header"
Element
- We use the HTML DOM to get the element with id="header"
- JavaScript changes the content of this element (innerHTML)
Change HTML Attributes
To change the attribute of an HTML element, use this syntax:
document.getElementById(
id
).
attribute=new attribute value
This example changes The src attribute of the element:
Example
Try it »
Example explained:
- The HTML document above contains an element with id="image"
Element
- We use the HTML DOM to get the element with id="image"
- JavaScript changes the attribute of this element (from "smiley.gif" to "landscape.jpg")
