I`m trying to copy a div html content to another element as a text , but when I try that it ignores the white spaces, any idea how that can be done?
here is my code:
HTML
<div id="parent">
<!-- Component: -->
<div id="component" >
<p >
Start Now
</p>
</div>
<!-- Code: -->
<div >
<h1 >Code:</h1>
<p id="code"></p>
</div>
</div>
JS
const component = document.getElementById("component")
const code = document.querySelector("#code")
code.innerText=component.innerHTML
What I get: What I get
What I want: what I want
CodePudding user response:
It's not that the whitespace is being ignored, but rather how the browser displays particular elements. HTML elements each have their own predefined styles & characteristics, typically defined via user agent stylesheets.
Given that you want to honor the whitespace, you can either use css attribute white-space
or change #code
to a <pre>
tag instead of a <p>
(downside is you will still need to override default browser styles).
const comp = document.getElementById('component');
const original = document.getElementById('codeoriginal');
const code = document.getElementById('code');
const code2 = document.getElementById('code2');
original.innerText = comp.innerHTML;
code.innerText = comp.innerHTML;
code2.innerText = comp.innerHTML;
#code {
white-space: pre;
}
<div id="parent">
<!-- Component: -->
<div id="component" >
<p >
Start Now
</p>
</div>
<!-- Code: -->
<div >
<h1 >Code: (Original)</h1>
<p id="codeoriginal"></p>
</div>
<div >
<h1 >Code: (CSS change)</h1>
<p id="code"></p>
</div>
<div >
<h1 >Code: (Using pre)</h1>
<pre id="code2"></p>
</div>
</div>