How do I create a new line in Javascript?
To inject a line break in HTML content, leverage the <br>
tag:
For text inputs or text areas, simply append the newline character '\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:
To append multiple lines, use a loop:
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:
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!
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
:
Was this article helpful?