1

i want to create a new line in "p" element . I have tried br tag and \n tag as well, but it didn't really work . when i run the code the new line appears as a space between the lines.

<p id="log"></p>
let log = document.getElementById("log");
let string = `|line1\n|line2`;
let array1 = string.split("|");
let i = 0;
let x = 0;
log.addEventListener("click", () => {
  document.addEventListener("keypress", type);
})

function type() {
  log.textContent += array1[i].charAt(x);
  x++;
  if (x === array1[i].length) {
    x = 0;
    i++;
  }
  if (array1[i] === undefined) {
    document.removeEventListener("keypress", type);
  }
}

1 Answers1

0

Because you are trying to get element before loading HTML, so the log variable is null in your code.

Please try this code.

<p id="log>hello</p>
window.onload = function init() {
  const log = document.getElementById("log");
  log.innerText = "\n first \n second";
};
Web dozens
  • 168
  • 1
  • 2
  • 8