Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Creating a multiline div with javascript

I am trying to make a function that creates divs containing text and puts them in another div called "history".
The problem is that the text in the divs come out as single lines like this

2/2=1
instead of this
2/2
=1
It may also be caused by the height limitation of the div, if so how do I automatically adjust the size with javascript.

function creatediv() {
  var element = document.createElement("div");
  var doc = "2/2" + "\n" + "=1";
  const es = element.style;
  element.appendChild(document.createTextNode(doc));
  document.getElementById('history').appendChild(element);
  es.backgroundColor = "azure";
  es.margin = "3px"
  es.borderRadius = "5px";
  es.padding = "2px"
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

  • Use the CSS property white-space: pre which makes line-breaks (and other whitespace) inside HTML #text nodes visible.
  • white-space is exposed in the DOM as CSSStyleDeclaration.whiteSpace.
    • Values are set as normal strings, e.g. 'pre' or 'normal'.
    • e.g.: document.getElementById('abc123').style.whiteSpace = 'pre';
  • You don't need element.appendChild(document.createTextNode(doc));, you can set .textContent directly.

Like so (click "Run code snippet"):

function createDiv() {

    const div = document.createElement("div");
    div.textContent = "2/2\n=1";

    const s = div.style;
    s.backgroundColor = "azure";
    s.margin          = "3px";
    s.borderRadius    = "5px";
    s.padding         = "2px";
    s.whiteSpace      = 'pre';  // <-- Right here.

    document.getElementById('history').appendChild( div );
}
<button type="button" onclick="createDiv()">Create DIV</button>

<div id="history" style="border: 3px inset #999"></div>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!