0

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"
}
5
  • 1
    Use white-space: pre;. Commented Dec 11, 2021 at 16:16
  • Or use an html line break <br/> instead of \n and set innerHTML Commented Dec 11, 2021 at 16:16
  • I ran your code and it outputs everything on a single line. I would assume that the text doesn't have enough width in your application, white-space:no-wrap would help force it stay on one line might cause overflow though Commented Dec 11, 2021 at 16:17
  • @ZohirSalak I think you read the question backwards. OP is expecting the ``\n` to display as multi line Commented Dec 11, 2021 at 16:20
  • wow, i should probably go lay down for a minute. Commented Dec 11, 2021 at 16:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

What is that format setting called?
@MaximilianDolbaum What do you mean by "format setting"?
that all the equal signs are below each other, if you didn't manually do it, it looks kinda neat
@MaximilianDolbaum That is entirely coincidental.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.