html get 在代码元素而不是字符串中呈现

html get's rendered inside code element instead of a string

我想为我的组件自动生成一个 html 预览,但是我的 html 被渲染为一个节点而不是显示一个字符串...

这是我的简化示例

const btns = document.querySelectorAll('.preview')
const previewContainer = document.getElementById('previewContainer')

const pre = document.createElement('pre')
previewContainer.appendChild(pre)

btns.forEach((btn)=> {
  const code = document.createElement('code')
  pre.appendChild(code)
  code.innerHTML = btn.outerHTML
  console.log(typeof btn.outerHTML)
})
<button class="preview">label1</button>
<button class="preview">label2</button>
<div id="previewContainer"></div>

还创建了一个codepen

使用innerText代替内部HTML

const btns = document.querySelectorAll('.preview')
const previewContainer = document.getElementById('previewContainer')

const pre = document.createElement('pre')
previewContainer.appendChild(pre)

btns.forEach((btn)=> {
  const code = document.createElement('code')
  pre.appendChild(code)
  code.innerText = btn.outerHTML
  console.log(typeof btn.outerHTML)
})
<button class="preview">label1</button>
<button class="preview">label2</button>
<div id="previewContainer"></div>

.innerHTML 将字符串解析为 HTML.innerText 将其保留为字符串并附加一个字符串而不是 HTML

使用textContent代替innerHTML

我不使用 innerText 因为

Don't get confused by the differences between Node.textContent and HTMLElement.innerText. Although the names seem similar, there are important differences:

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows “human-readable” elements.

textContent returns every element in the node. In contrast, innerText is aware of styling and won’t return the text of “hidden” elements.

Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)

const btns = document.querySelectorAll('.preview')
const previewContainer = document.getElementById('previewContainer')

const pre = document.createElement('pre')
previewContainer.appendChild(pre)

btns.forEach((btn)=> {
  const code = document.createElement('code')
  pre.appendChild(code)
  code.textContent = btn.outerHTML; // show the code as text
  console.log(typeof btn.outerHTML)
})
<button class="preview">label1</button>
<button class="preview">label2</button>
<div id="previewContainer"></div>