Home > Enterprise >  Creating a multiline div with javascript
Creating a multiline div with javascript

Time:12-12

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

CodePudding user response:

  • 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>

  • Related