JavaScript HTML DOM - Changing HTML
The HTML DOM allows JavaScript to modify the content and attributes of HTML elements.
Changing HTML Content
The simplest 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:
document.getElementById(id).innerHTML = "new HTML";
Example 1: Changing a <p> Element
This example changes the content of a <p> element:
Explanation:
- The HTML document contains a <p> element with the id "p1".
- JavaScript uses the HTML DOM to get the element with id "p1".
- The content (innerHTML) of that element is changed to "New text!".
Example 2: Changing an <pre style="display: inline"><h1></pre> Element
This example changes the content of an <pre style="display: inline"><h1></pre> element:
document.getElementById(id).attribute = "new value";
Example: Changing the src Attribute of an <img> Element
This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html><body>
<img id="myImage" src="smiley.gif">
<script>document.getElementById("myImage").src = "landscape.jpg"
;</script></body></html>
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif"><script>document.getElementById("myImage").src = "landscape.jpg";</script>
</body>
</html>
Explanation:
- The HTML document contains an <img> element with the id "myImage".
- JavaScript uses the HTML DOM to get the element with id "myImage".
- The src attribute of that element is changed from "smiley.gif" to "landscape.jpg".
Dynamic HTML Content
JavaScript can create dynamic HTML content. For example, displaying the current date and time:
<!DOCTYPE html><html>
<body><p id="demo">
</p><script>document.getElementById("demo").innerHTML = "Date: " + Date();
</script>
</body
></html>
document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
<!DOCTYPE html>
<html>
<body>
<p>Bla bla bla
</p><script>document.write(Date());
</script>
<p>Bla bla bla</p>
</body>
</html>
Note: Never use document.write() after the document is loaded as it will overwrite the entire document.
Test Yourself With Exercises
Exercise:
Use the HTML DOM to change the value of an image's src attribute.
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src = "pic_mountain.jpg";
</script>