Explain Codes LogoExplain Codes Logo

How do I create a new line in Javascript?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Oct 19, 2024
TLDR

To inject a line break in HTML content, leverage the <br> tag:

document.getElementById("container").innerHTML += "<br>";

For text inputs or text areas, simply append the newline character '\n':

document.querySelector("textarea").value += "\n";

Determining the context: "\n" vs "
"

The character '\n' is ideal for preformatted contexts such as <pre> tags, text areas or console logs, where it represents a new line. When dealing with HTML content, <br> should be your go-to approach for creating new lines.

Creating new lines in the DOM

Instead of using document.write, which has the potential to clear existing HTML content, opt for direct DOM manipulation:

let newLine = document.createElement("br"); // creates new line document.body.appendChild(newLine); // adds new line to the body

To append multiple lines, use a loop:

let content = document.getElementById("content"); for (let i = 0; i < 3; i++) { // Add 3 line breaks 'cause we love some space! content.appendChild(document.createElement("br")); }

New lines & CSS: The dynamic duo

With CSS, text formatting becomes a tad easier. The white-space: pre; property preserves both spaces and line breaks, rendering the '\n' as a line break within HTML:

preformatted { white-space: pre; }

Looping with newlines for the wow effect!

Often, you need to generate beautiful text patterns involving line breaks. For instance, a star pyramid. Let's use loops and '\n' to create one. Code, stars, and loops - oh my!

let pyramid = ""; for(let i = 1; i <= 5; i++){ pyramid += "*".repeat(i) + '\n'; // newline adds the magic here! } console.log(pyramid); // Logs our beautiful star pyramid. Isn't it stellar?

Printed in a <pre> tag or console, it looks like a bona fide pyramid, thanks to our nifty newline characters.

"document.write"? Nah, we got better!

In dynamic web apps, document.write is a no-no. It's 2022, mates! Let's embrace modern options like:

  • Node.textContent for super-safe text addition, sans HTML tag interpretation.
  • Element.innerHTML for pouring in some sweet HTML.

Enter the <p>

For demarcating content sections, use <p>. It creates a concrete break, providing space between text chunks. It's more than a line break; it's a sign of a fresh idea!

Mastering whitespace with output containers

In output containers like div and pre, '\n' will work wonders if the container's white-space property is dressed in pre or pre-wrap:

let outputContainer = document.getElementById('output'); outputContainer.style.whiteSpace = 'pre'; // Let's respect the whitespaces! outputContainer.textContent += 'First line.\nSecond line.'; // Yep, newline doing its line-break dance.