如何将一个元素的外部HTML显示为另一个元素的内容

How to display the outerHTML of an element as a content of another one element?

本文关键字:元素 显示 HTML 另一个 外部 一个      更新时间:2023-09-26

我想将outerHTML的结果直接"打印"到网页上,但它写入的是outerHTML的结果而不是"代码"。

好吧,很容易将其显示在console.logalert窗口中,但我想将其写入页面。

document.getElementById("oneId").innerHTML = 
   "The outerHTML of oneId is :" +document.getElementById("anotherId").outerHTML;

结果必须是:

The outerHTML of oneId is : <div id="oneId"></div>

你必须使用.textContent而不是.innerHTML

document.getElementById("oneId").textContent = 
     "The outerHTML of oneId is :" + document.getElementById("anotherId").outerHTML;

如果使用 .innerHTML ,则赋值字符串将呈现为 html 元素而不是纯文本。