JavaScript中document.getElementById和document.write

1、操作HTML元素

JavaScript访问某个HTML元素,可以使用document.getElementById(id)方法。

eg:

    1. <!DOCTYPE html>
    2. <html>
    3. <body> 
    4. <p id="demo">Hello</p>
    5. <script>
    6. document.getElementById("demo").innerHTML="Hello world";
    7. </script>
    8. </body>
    9. </html>

2、写到文档输出

JavaScript写到文档输出,可以使用document.write('HTML内容')方法。

eg:

    1. <!DOCTYPE html>
    2. <html>
    3. <body>
    4. <script>
    5. document.write("<p>Hello world</p>");
    6. </script>
    7. </body>
    8. </html>

注意:

请使用 document.write() 仅仅向文档输出写内容。

如果在文档已完成加载后执行 document.write,整个 HTML 页面将被覆盖:

<!DOCTYPE html>
<html>
<body>
<p>Hello world</p>
<button onclick="myFunction()">点击这里</button>
<script>
function myFunction(){
document.write("糟糕!消失了。");
}
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/xiajiejie/p/9866581.html