JavaScript HTML DOM - Changing HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing HTML Output Stream
JavaScript can create dynamic HTML content:
Today's date is:
In JavaScript, document.write()
can be used to write directly to the HTML output stream.
Example
| | Never use document.write()
after the document (DOM) has finished loading. This will overwrite the document. |
| --- | --- |
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML
property.
To change the content of an HTML element, use this syntax:
This example changes the content of a <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 an <h1>
element:
Example
Example explanation:
- The HTML document above contains an
<h1>
element withid="header"
- We use the HTML DOM to get the element with
id="header"
- JavaScript changes the content (innerHTML) of this element
Changing HTML Attributes
To change the attribute of an HTML element, use this syntax:
This example changes the src
attribute of an <img>
element:
Example
Example explanation:
- The HTML document above contains an
<img>
element withid="image"
- We use the HTML DOM to get the element with
id="image"
- JavaScript changes the attribute of this element (changes "smiley.gif" to "landscape.jpg")