Как добавить новую строку в <div> Javascript?

Рейтинг: -1Ответов: 2Опубликовано: 15.02.2023

Как добавить абзац в в Javascript?

var pElement = document.createElement("div");
var solveBlock = document.getElementById("solveBlock");
pElement.className = "steps"
let randint = 100; 
let answer = 0;
while (randint > 0){
  pElement.textContent += '\n';
  pElement.textContent += randint + ' : 2 = ' + Math.floor(randint / 2) + ' целых, ' + randint % 2 + ' в остатке';
  answer = randint % 2 + answer
  randint = Math.floor(randint / 2);
}
solveBlock.appendChild(pElement);
<div id="solveBlock">
</div>
Вот такую штуковину желательно бы сделать рабочей, чтобы добавляла абзац в див, так как в данный момент это она не выполняет. Нужно чтобы она добавляла в перенос на новую строку, и потом добавляла текст, но новой строки не добавляется, лишь текст.

Ответы

▲ 0

Надо заменить \n на <br /> и вставлять в innerHTML, тогда будет перенос строк

var pElement = document.createElement("div");
var solveBlock = document.getElementById("solveBlock");
pElement.className = "steps"
let randint = 100; 
let answer = 0;
while (randint > 0) {      
  pElement.innerHTML += randint + ' : 2 = ' + Math.floor(randint / 2) + ' целых, ' + randint % 2 + ' в остатке';
  pElement.innerHTML += '<br />';
  answer = randint % 2 + answer
  randint = Math.floor(randint / 2);
}
solveBlock.appendChild(pElement);
<div id="solveBlock">
</div>

▲ 0

Как добавить абзац в в Javascript?

Если нужны новые элементы - их нужно создавать прямо в цикле

const solveBlock = document.getElementById("solveBlock");
let randint = 100;
let answer = 0;
while (randint > 0) {
  const pElement = document.createElement("div");
  pElement.className = "steps"
  pElement.textContent += randint + ' : 2 = ' + Math.floor(randint / 2) + ' целых, ' + randint % 2 + ' в остатке';
  answer = randint % 2 + answer
  randint = Math.floor(randint / 2);
  solveBlock.appendChild(pElement);
}
<div id="solveBlock">
</div>