English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In some cases, you may need to generate output from JavaScript code. For example, you may want to view the value of a variable, or write a message to the browser console to help you debug problems in the JavaScript code that is running, etc.
In this tutorial, you will learn how to generate output in JavaScript.
JavaScript can display data in different ways:
to write to an HTML element using innerHTML
to write to the document stream using document.write()
Pop up a warning box using window.alert()
to write to the browser console using console.log()
You can use the element'sinnerHTMLproperties to write or insert output within HTML elements.
However, before writing the output, we need to use such asgetElementById()such methods to select elements.
<p id="msg"></p> <p id="output"></p> <script> document.getElementById("msg").innerHTML = "Hello World"; document.getElementById("output").innerHTML = 20 + 30; </script>Test see‹/›
Using innerHTML to change the HTML content of an element is a common method to display data in HTML.
You can only usedocument.write()The method parses the content into the current document.
<script> document.write("Hello world<br>"); document.write("}}"20 + 30); </script>Test see‹/›
Ifdocument.write()Use this method after the page is loaded, it will overwrite all existing content in the document.
<script> function myFunc() { document.write("<p>test document.write().</p> } </script>Test see‹/›
You can also use an alert dialog box to display messages or output data to the user.
Usealert()The method will create an alert dialog box.
<button onclick="alert('Hello world');">alert</button>Test see‹/›
You can useconsole.log()Methods can easily output messages or write data to the browser console.
This console can be used for testing or debugging purposes.
<script> console.log("Hello world"); console.log(20 + 30); </script>Test see‹/›
To access the Web browser's console, first pressF12Press the keys on the keyboard to open the developer tools, then click the Console tab.
You will learn more about debugging in the later part of this tutorial.