How to add a BR dynamically in JavaScript.

When using JavaScript, we frequently find ourselves looking to manipulate the DOM after the page has rendered. When we want to create line breaks the <br /> element is typically used.

But how can we create this element dynamically in JavaScript? To add a BR in JavaScript the method createElement() is used. We can use it within our document and append the line break to the DOM like so:

const testElement = document.querySelector('div');
const lineBreak = document.createElement('br');

And there you have it, createElement() serves as a useful method to create any HTML element on the fly.

Proudly published with Gatsby