JavaScript allows developers to dynamically modify web page content and structure using the DOM. Adding line breaks in JavaScript is a common task used to format text output and improve readability in web applications.
- Line breaks can be added using the <br> HTML tag in JavaScript.
- The \n newline character is also used for line breaks in text-based outputs.
- Different approaches are used depending on whether the output is displayed in HTML or the console.
These are the following approaches:
Using innerHTML
Here, we are using the innerHTML property in JavaScript to add a line break (<br>) dynamically to the content of an HTML element with the ID "geeksTitle." This allows us to modify the HTML content directly from JavaScript, making it a straightforward method for adding visual elements like line breaks.
Example: This uses innerHTML to add a Line Break in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example 1</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1 id="geeksTitle">GeeksforGeeks</h1>
<h3>Approach 1: Using innerHTML</h3>
<button onclick="addLineBreak()">Add Line Break</button>
<script>
function addLineBreak() {
const title = document.getElementById('geeksTitle');
title.innerHTML += '<br>';
}
</script>
</body>
</html>
Using createTextNode and appendChild
Here, we are using JavaScript's createTextNode and appendChild methods to dynamically add a line break (<br>) to the HTML DOM. The addLineBreak function targets the <h3> element with the id "approachTitle" and inserts the line break before its next sibling, which in this case is the button.
Example: This uses createTextNode and appendChild to add a Line Break in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example 2</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1 id="geeksTitle">GeeksforGeeks</h1>
<h3 id="approachTitle">Approach 2: Using createTextNode
and appendChild</h3>
<script>
function addLineBreak() {
const approachTitle = document.getElementById('approachTitle');
const lineBreak = document.createElement('br');
approachTitle.parentNode
.insertBefore(lineBreak, approachTitle.nextSibling);
}
</script>
<button onclick="addLineBreak()">Add Line Break</button>
</body>
</html>