Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading