Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

87
Views
Can I copy innerHTML for a div without ignoring white spaces?

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" class="">
    <p class="px-8 text-center py-2  bg-green-500 text-white 
              dark:bg-green-50 dark:text-green-900
              font-medium text-lg rounded-md 
              hover:scale-105 hover:bg-green-100
              ">
      Start Now
    </p>
  </div>

<!-- Code: -->

  <div class="px-8 my-8">
      <h1 class="text-white ">Code:</h1>
      <p class="text-white" 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

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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" class="">
    <p class="px-8 text-center py-2  bg-green-500 text-white 
              dark:bg-green-50 dark:text-green-900
              font-medium text-lg rounded-md 
              hover:scale-105 hover:bg-green-100
              ">
      Start Now
    </p>
  </div>

<!-- Code: -->

  <div class="px-8 my-8">
      <h1 class="text-white ">Code: (Original)</h1>
      <p class="text-white" id="codeoriginal"></p>
  </div>

  <div class="px-8 my-8">
      <h1 class="text-white ">Code: (CSS change)</h1>
      <p class="text-white" id="code"></p>
  </div>
  
  <div class="px-8 my-8">
      <h1 class="text-white ">Code: (Using pre)</h1>
      <pre class="text-white" id="code2"></p>
  </div>
</div>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs