JavaScript HTML

JavaScript HTML DOM - Changing HTML

HTML DOM allows JavaScript to change the content of HTML elements.

Change the HTML output stream

JavaScript can create dynamic HTML content:

Today’s date is: Wed Oct 26 2016 10:01:53 GMT+0800 (China Standard Time)

In JavaScript, document.write() can be used to write content directly to the HTML output stream.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
document.write(Date());
</script>
</body>
</html>

Never use document.write() after the document has been loaded. This will overwrite the document.

Change HTML content

The simplest way to modify HTML content is to use the innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML=new HTML

This example changes <h1> ; Element content:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="新标题";
</script>
</body>
</html>

Example explanation:

The above HTML document contains the <h1> element with id="header"
We use HTML DOM to obtain id="header" " element
JavaScript Change the content of this element (innerHTML)

Change the HTML attributes

If you need to change the attributes of the HTML element, Please use this syntax:

document.getElementById(id).attribute=new attribute value

This example changes the src attribute of the <img> element:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
<p>原图片为 smiley.gif,脚本将图片修改为 landscape.jpg</p>
</body>
</html>

Example Explanation:

The above HTML document contains the <img> element with id="image"

We use HTML DOM to obtain the element with id="image"

JavaScript Change the attributes of this element (change "../style/images/smiley.gif" to "../style/images/landscape.jpg")


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="新文本!"; </script> <p>以上段落通过脚本修改文本。</p> </body> </html>
submitReset Code