Writing text to a document in JavaScript
Using JavaScript, you can manage the HTML page tags, for example, display text in them. We will learn this later when we go through the section on working with the DOM.
Sometimes, however, for debugging purposes,
you want to display some text in the browser
window. This is done with the document.write
command. Let's see how it works with examples.
Example
Output a numeric value:
document.write(123);
Example
Let's output some text:
document.write('text');
Example
Display text enclosed in tags:
document.write('<b>text</b>');
Example
Let's output the text contained in the variable:
let str = 'text';
document.write(str);
Example
Enclose the text from the variable in tags:
let str = 'text';
document.write('<b>' + str + '</b>');
Example
Display text in two rows:
document.write('text <br> text');
Example
Let's display a lot of texts in a column:
document.write('text1<br>');
document.write('text2<br>');
document.write('text3<br>');
Example
It's also possible like this:
document.write('text');
document.write('<br>');
document.write('text');
Practical tasks
Display some text in the browser window.
Display some text in the browser window, making it italic.
Given a variable:
let str = 'text';
Display the text from the variable in the browser window so that it is italic.
Display a column of numbers from 1
to 5
in the browser window.