Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

302
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda