In this blog post, we’ll discuss how to create a line break (also known as <br>) in JavaScript. Line breaks are useful when you want to separate content on the page.
Creating a Line Break with JavaScript
Let’s say you have a <div> with an ID of “content”, and you want to display some text with a line break between two phrases. You can achieve this using JavaScript by creating a new Text node for each phrase, and a new HTMLBRElement node for the line break.
Here’s an example:
<script> // Get the content div const contentDiv = document.getElementById("content"); // Create a new Text node for the first phrase const text1 = document.createTextNode("This is the first line."); // Create a new HTMLBRElement node for the line break const br = document.createElement("br"); // Create a new Text node for the second phrase const text2 = document.createTextNode("This is the second line."); // Append the Text and HTMLBRElement nodes to the content div contentDiv.appendChild(text1); contentDiv.appendChild(br); contentDiv.appendChild(text2); </script>
After running this script, your <div> will look like this:
<div id="content"> This is the first line. <br> This is the second line. </div>
Using InnerHTML
Another way to create a line break is by using the innerHTML property. Keep in mind, however, that this method can potentially expose your webpage to cross-site scripting (XSS) attacks if you’re using user-generated content.
Here’s an example of using innerHTML to create a line break:
<script> // Get the content div const contentDiv = document.getElementById("content"); // Set the innerHTML with a line break contentDiv.innerHTML = "This is the first line.<br>This is the second line."; </script>
Just like the first example, this will result in the following output:
<div id="content"> This is the first line. <br> This is the second line. </div>
Conclusion
In this blog post, we’ve learned two different ways to create a line break in JavaScript. The first method involves creating new Text and HTMLBRElement nodes and appending them to the desired element. The second method uses the innerHTML property to directly set the content with a line break. Choose the method that best suits your needs and always be cautious when using user-generated content with innerHTML to avoid potential security risks.