1. 首页
  2. 软件开发
  3. document.write和innerHTML、innerText 的区别?

document.write和innerHTML、innerText 的区别?

  • 发布于 2024-09-26
  • 1 次阅读


  1. document.write:

  2. document.write 是一个方法,用于向文档中写入内容。

  3. 它可以直接在 HTML 文档中使用,将内容直接输出到页面上。

  4. 但是,如果在页面加载完成后再使用 document.write 方法,它会覆盖整个文档内容,可能会导致页面结构混乱。

  5. 2.innerHTML:

  6. innerHTML 是一个属性,用于获取或设置元素的 HTML 内容。

  7. 可以通过 innerHTML 属性来改变元素的内容,而不会影响元素本身。

  8. innerHTML 只能用于 HTML 元素,不能用于文档节点。

  9. 3.innerText:

  10. innerText 是一个属性,用于获取或设置元素的文本内容。

  11. innerText 会忽略元素中的 HTML 标签,只返回文本内容。

  12. innerText 适用于需要处理纯文本内容的情况,但在某些情况下可能会受到浏览器的支持程度影响。



    <title>Document.write vs innerHTML vs innerText</title>
    


    <div id="output"></div>
    
    <script>
        // 使用 document.write
        document.write("Hello, document.write!");
    
        // 使用 innerHTML
        document.getElementById("output").innerHTML = "<p>Hello, innerHTML!</p>";
    
        // 使用 innerText
        document.getElementById("output").innerText = "Hello, innerText!";
    </script>
    


document.write 用于向文档中写入内容,会直接输出到页面上,可能会导致页面结构混乱。 innerHTML 和 innerText 用于获取或设置元素的内容,innerHTML 可以处理 HTML 内容,而 innerText 只处理纯文本内容。

原文链接: https://blog.csdn.net/hexadecimal_001/article/details/138215142