JavaScript HTML DOM changes HTML content
HTML DOM allows JavaScript to change the content of the HTML element.
Change the HTML output stream
JavaScript can create dynamic HTML content:
Today's date is:
In JavaScript, document.write () can be used to directly write HTML content to the output stream.
Examples
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
try it"
Never use document.write after the document has finished loading (). This overrides the document. |
Change the HTML content
Using innerHTML property The easiest way to modify the HTML content.
To change the content of the HTML element, use this syntax:
document.getElementById(id).innerHTML=新的 HTML
This example changes the contents of the <p> element:
Examples
<Html>
<Body>
<P id = "p1"> Hello World! </ P>
<Script>
document.getElementById ( "p1") innerHTML = "new text!.";
</ Script>
</ Body>
</ Html>
<Body>
<P id = "p1"> Hello World! </ P>
<Script>
document.getElementById ( "p1") innerHTML = "new text!.";
</ Script>
</ Body>
</ Html>
try it"
This example changes the contents of the <h1> element:
Examples
<!DOCTYPE html>
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="新标题";
</script>
</body>
</html>
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="新标题";
</script>
</body>
</html>
try it"
Examples to explain:
- The above HTML document that contains id = "header" of the <h1> element
- We use the HTML DOM to get the id = "header" element
- JavaScript changes on this element contents (innerHTML)
Change the HTML attributes
To change the properties of an HTML element, use this syntax:
document.getElementById(id).attribute=新属性值
This example changes the src attribute <img> element:
Examples
<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
try it"
Examples to explain:
- The above HTML document that contains id = "image" of the <img> element
- We use the HTML DOM to get the id = "image" element
- JavaScript change the properties of this element (the "smiley.gif" to "landscape.jpg")