Search code examples
javascriptline-breaks

How to add a line break in JavaScript?


I need to add text to a webpage using javascript so I've done it as follows

// Create name as h1
var h = document.createElement('h1');
var t = document.createTextNode('Austin Chandler');
h.appendChild(t);
document.body.appendChild(h);

// Formatting h1 tag
document.querySelector('h1').style.color = 'red';
document.querySelector('h1').style.fontFamily = 'Tahoma';
document.querySelector('h1').style.textAlign = 'center';

// Line break
document.write('\n');

// Create course and section number as h2
var h_2 = document.createElement('h2');
var t_2 = document.createTextNode('WEB 115 - Section 0001');
h.appendChild(t_2);
document.body.appendChild(h_2);

// Formatting h2 tag
document.querySelector('h2').style.color = 'red';
document.querySelector('h2').style.fontFamily = 'Garamond';
document.querySelector('h2').style.fontStyle = 'italics';
document.querySelector('h2').style.textAlign = 'center';

document.write('\n'); only adds a small space between my text "Austin Chandler" and "WEB 115 - Section 0001" not a line break.

Output should look as follows:
Austin Chandler
WEB 115 - Section 0001

The current output looks like this:
Austin Chandler WEB 115 - Section 0001

What can I do to add a line break?


Solution

  • Use document.body.appendChild(document.createElement("br")); instead of \n

    But also, you are adding all your text to h1. You want the second text in the h2 element:

    // Create name as h1
    var h = document.createElement('h1');
    var t = document.createTextNode('Austin Chandler');
    h.appendChild(t);
    document.body.appendChild(h);
    
    // Formatting h1 tag
    document.querySelector('h1').style.color = 'red';
    document.querySelector('h1').style.fontFamily = 'Tahoma';
    document.querySelector('h1').style.textAlign = 'center';
    
    // Line break
    document.body.appendChild(document.createElement("br"));
    
    // Create course and section number as h2
    var h_2 = document.createElement('h2');
    var t_2 = document.createTextNode('WEB 115 - Section 0001');
    
    // here change h to h2:
    h_2.appendChild(t_2);
    
    
    document.body.appendChild(h_2);
    
    // Formatting h2 tag
    document.querySelector('h2').style.color = 'red';
    document.querySelector('h2').style.fontFamily = 'Garamond';
    document.querySelector('h2').style.fontStyle = 'italics';
    document.querySelector('h2').style.textAlign = 'center';