JavaScript Introduction | Overview | JavaScript Output

JavaScript Output

JavaScript can output results to an HTML page in several ways. The output methods available in JavaScript are as follows.

  1. window.alert() method
  2. innerHTML property using HTML DOM elements
  3. document.write() method
  4. console.log() method

window.alert() Method

The simplest way to output data in JavaScript is to use the window.alert() method. The window.alert() method opens a dialog box separate from the browser and delivers data to the user.

<script>
    function alertDialogBox() {
        alert("You cannot do anything else until you press OK!");
    }
</script>

When using any method or property of the window object, the window prefix can be omitted.

innerHTML Property Using HTML DOM Elements

The most commonly used output method in actual JavaScript code is to use the innerHTML property with HTML DOM elements.

First, select an HTML element by using a method of the document object such as getElementByID() or getElementsByTagName(). Then, by using the innerHTML property, you can easily change the content or attribute values of the selected HTML element.

<script>
    var str = document.getElementById("text");
    str.innerHTML = "It has changed to this sentence!";
</script>

document.write() Method

When the document.write() method runs while a web page is loading, it outputs data first on the web page. Therefore, document.write() is mostly used for testing or debugging.

<script>
    document.write(4 * 5);
</script>

However, if the document.write() method runs after all content on the web page has loaded, it deletes all data previously loaded on the web page and outputs its own data. Therefore, when using document.write() for purposes other than testing, it must be used with sufficient caution.

<button onclick="document.write(4 * 5)">Press the button!</button>

console.log() Method

The console.log() method outputs data through the web browser’s console.

In most major web browsers, you can use the console screen by pressing F12 and then clicking Console in the menu. Outputting data through this console screen provides more detailed information, which is very helpful for debugging.

<p>Press F12 and open the console screen to check the result.</p>
<script>
    console.log(4 * 5);
</script>