JavascriptHTML DOM-changing HTML
The HTML DOM allows JavaScript to change the contents of an HTML element.
Changing the HTML output stream
JavaScript is able to create dynamic HTML content:
Today's date is: Mon June 18:23:35 gmt+0800 (China Standard Time)
In JavaScript, document.write () can be used to write content directly to the HTML output stream.
Example <! DOCTYPE html>
<body>
<script>
document.write (Date ());
</script>
</body>
Try it»
|
Never use document.write () after the document has finished loading. This overwrites the document. |
Change HTML Content
The simplest way to modify HTML content is to use the InnerHTML property.
To change the contents of an HTML element, use this syntax:
document.getElementById (
ID). innerhtml=
New HTML
This example changes the contents of the <p> element:
Examples <body>
<p id= "P1" >hello world!</p>
<script>
document.getElementById ("P1"). Innerhtml= "New text!";
</script>
</body>
Try it»
This example changes the contents of the
Example <! DOCTYPE html>
<body>
<script>
var Element=document.getelementbyid ("header");
Element.innerhtml= "New Header";
</script>
</body>
Try it»
Example Explanation:
- The above HTML document contains the
- We use the HTML DOM to get the id= "header" element
- JavaScript changes the contents of this element (InnerHTML)
Changing HTML Properties
To change the attributes of an HTML element, use this syntax:
document.getElementById (
ID).
attribute=new Value
This example changes the SRC attribute of the element:
Example <! DOCTYPE html>
<body>
<script>
document.getElementById ("image"). src= "Landscape.jpg";
</script>
</body>
Try it»
Example Explanation:
- The above HTML document contains the elements of the id= "image"
- We use the HTML DOM to get the elements of the id= "image"
- JavaScript changes the attributes of this element (change "smiley.gif" to "landscape.jpg")
JavaScript HTML DOM-changing HTML