DOM 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:

Tue Oct 18 2016 09:59:23 GMT+0800


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

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<script>
document.write(Date());
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

lampNever 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 the content of the <p> element:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="新文本!";
</script>
<p>以上段落通过脚本修改文本。</p>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example

This example changes the content of the <h1> element:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<h1 id="header">旧标题</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="新标题";
</script>
<p>"旧标题" 被 "新标题" 取代。</p>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example

Example explanation:

  • The above HTML document contains the <h1> element with id="header"


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


  • JavaScript Change the content of this element (innerHTML)



Change HTML attributes

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

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

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

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<img id="image" src="/upload/course/000/000/009/580469a2a27e3327.gif" width="160" height="120">
<script>
document.getElementById("image").src="/upload/course/000/000/009/58058303e12c0481.jpg";
</script>
<p>原图片为 /upload/course/000/000/009/580469a2a27e3327.gif,脚本将图片修改为/upload/course/000/000/009/58058303e12c0481.jpg</p>

</body>
</html>

Running example »

Click the "Run Example" button to view the online example

Example explanation:

  • The above HTML document contains id= The <img> element of "image"

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

  • JavaScript to change this element Attributes (change "/upload/course/000/000/009/58058303e12c0481.jpg" to "/upload/course/000/000/009/580469a2a27e3327.gif
    ")