I want to auto-generate a html-preview for my components, but my html gets rendered as a node instead of displaying a string...
this is my simplified example
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>
Have also created a codepen
Use textContent instead of innerHTML
I do not use innerText because
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>