cerbin cerbin - 2 months ago 7
HTML Question

Rewriting elements in html by innerHTML

i have a a code like that:

<p id = "outputLaps"></p>


JS:

document.getElementById("outputLaps").innerHTML = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds


and i don't want to rewrite it, but to display it under the previous "lap".
Thanks for answers :).

Answer

Use insertAdjacentHTML when you want to insert HTML.

var str = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds;
document.getElementById("outputLaps").insertAdjacentHTML("beforeend", str);

However, if you only want to insert text, you can append a text node:

var str = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds;
document.getElementById("outputLaps").appendChild(
  document.createTextNode(str)
);

In case you want the text to go to the next line, you can either

  • Insert a newline character \n and style the paragraph with white-space set to pre, pre-wrap or pre-line.
  • Insert a <br /> HTML element.
  • Use different paragraphs. Seems the most semantic.