JavaScript HTML DOM - Change HTML
HTML DOM allows JavaScript to change the content of HTML elements.
Change the HTML output stream
JavaScript is able to create dynamic HTML content:
Today's date is:
Thu Feb 25 2016 19:25:10 GMT+0800
In JavaScript, document.write() can be used to stream content directly to HTML.
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Try it out . . .
Never use document.write() after the document is loaded. This overrides the document. |
Change the HTML content
The easiest way to modify HTML content is to use the innerHTML property.
To change the contents of HTML elements, use this syntax:
This example changes the contents of the element:
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
Try it out . . .
This example changes the contents of the element:
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="New Header";
</script>
</body>
</html>
Try it out . . .
Examples:
-
The HTML document above contains the element of id"header"
-
We use HTML DOM to get the element of id"header"
-
JavaScript changes the contents of this element (innerHTML)
Change the HTML property
To change the properties of HTML elements, use this syntax:
This example changes the src property of the element:
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
Try it out . . .
Examples:
-
The HTML document above contains the element of the id"image" of the .lt;img>
-
We use HTML DOM to get the element of id"image"
-
JavaScript changes the properties of this element (change "smiley.gif" to "landscape.jpg")