Add new line to html from js
You can add a new line to an HTML document from JavaScript using the innerHTML
property or by creating a new element and appending it to the document.
Method 1: Using innerHTML
const paragraph = document.getElementById("myParagraph");
paragraph.innerHTML += "<br>"; // adds a new line
This method is simple and easy to use, but it can be slow if you're adding a large amount of content to the page.
Method 2: Creating a new element and appending it
const newLine = document.createElement("br");
document.getElementById("myParagraph").appendChild(newLine);
This method is more efficient than using innerHTML
and gives you more control over the new element.
Method 3: Using insertAdjacentHTML
const paragraph = document.getElementById("myParagraph");
paragraph.insertAdjacentHTML("beforeend", "<br>");
This method is similar to innerHTML
, but it's more efficient and allows you to specify where the new content should be inserted.
Example HTML
<p id="myParagraph">Hello World!</p>
Example JavaScript
const paragraph = document.getElementById("myParagraph");
paragraph.innerHTML += "<br>"; // or paragraph.appendChild(document.createElement("br")); or paragraph.insertAdjacentHTML("beforeend", "<br>");
This will add a new line to the paragraph element.
Note: Make sure to replace myParagraph
with the actual ID of the element you want to add the new line to.