JavaScript Output
JavaScript does not have any print or output functions.
JavaScript Display Data
JavaScript can output data in different ways:
Use window.alert() to pop up an alert box.
Use document.write() to write content into the HTML document.
Use innerHTML to write into an HTML element.
Use console.log() to write into the browser's console.
Using window.alert()
You can pop up an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Manipulating HTML Elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Please use the "id" attribute to identify the HTML element and innerHTML to get or insert the element content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My first paragraph</p>
<script>
document.getElementById("demo").innerHTML = "Paragraph has been modified.";
</script>
</body>
</html>
The above JavaScript statements (inside the <script> tag) can be executed in a web browser:
document.getElementById("demo") is JavaScript code that uses the id attribute to find the HTML element.
innerHTML = "Paragraph has been modified." is JavaScript code used to modify the element's HTML content (innerHTML).
In This Tutorial
In most cases, in this tutorial, we will use the methods described above to output:
The example above directly writes the <p> element with id="demo" to the HTML document output:
Writing to the HTML Document
For testing purposes, you can write JavaScript directly into the HTML document:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(Date());
</script>
</body>
</html>
| | Use document.write() only to output content to the document. If document.write is executed after the document has finished loading, the entire HTML page will be overwritten. | | --- | --- |
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.write(Date());
}
</script>
</body>
</html>
Writing to the Console
If your browser supports debugging, you can use the console.log() method to display JavaScript values in the browser.
Use F12 in the browser to enable debugging mode, and click on the "Console" menu in the debugging window.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Example console screenshot:
Did You Know?
| | Debugging in a program is the process of testing, finding, and reducing bugs (errors). | | --- | --- |