JavaScript: the difference between document.write() and innerHTML

 

document.write和innerHTML

The main difference: document.write is the content stream that directly writes the content to the page, which will cause all the page to be redrawn, while innerHTML writes the content to a DOM node, which will not cause all the page to be redrawn

 

Here are two examples to illustrate, the first example uses the write() method, and the second example uses innerHTML

 

Example 1: The page has initial content, click the button on the page to write the content to the page through the document.write() method, you will find that the original initial content has disappeared, and the entire page is only left with the write() method. content. The reason is that the entire page is redrawn

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

initial content


<button onclick="fun()" >按鈕</button>


<script>
    function fun() {
        document.write("write内容");
    }

</script>

</body>
</html>

 

 

 

Effect dynamic diagram:

 

 

Example 2: The page has initial content, a node is given after the initial content, and the content is written to this node through innerHTML, the initial content does not disappear, and the newly added content through innerHTML is accurately displayed at the node position

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

Initial content <a id= " p " ></a>


<button onclick="fun()">按钮</button>


<script>
    function fun() {
       document.getElementById( " p " ).innerHTML= " Newly added innerHTML content " ;
    }

</script>

</body>
</html>

 

Effect dynamic diagram:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324500769&siteId=291194637