Skip to main content

JavaScript Output Display Methods

By SamK
0
0 recommends
Category(s)
Topic(s)

JavaScript can display data in several ways:

  • innerHTML: Inserts content into an HTML element.
  • document.write(): Writes directly to the document output.
  • window.alert(): Displays data in an alert box.
  • console.log(): Logs messages or data to the browser console, commonly used for debugging. 

innerHTML

The innerHTML method is used to specify the HTML Content of an HTML element.

Example:

<html>
<body>

<p id="sum"></p>

<script>
document.getElementById("sum").innerHTML = 5 + 10 ;
// HTML output: <p id="sum">15</p>
</script>

</body>
</html>

document.write()

For quick testing, the document.write() method can be a handy tool.

<!DOCTYPE html>
<html>
<body>

<script>
document.write(10 + 5); // Output: 15
</script>

</body>
</html>

Overwriting the Whole HTML Page Content

Using document.write() after the HTML document has finished loading will overwrite and remove all existing content on the page.

<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my First Website.</h1>
<p>Welcome to my first paragraph.</p>

<button type="button" onclick="document.write(10 + 5)">Click Me</button> 

</body>
</html>

Document Dot Write Method Demo

The document.write() method is intended for testing purposes only.

window.alert()

The window.alert() method is used to show data in an alert box.

<!DOCTYPE html>
<html>
<body>

<script>
// This will display an alert box with the result of the addition
window.alert(10 + 5);
</script>

</body>
</html>

Window Dot Alert Method Demo

console.log()

To assist with debugging in a browser, you can use the console.log() method to output data or messages to the console.

<!DOCTYPE html>
<html>
<body>

<script>
console.log(10 + 5); // Output: 15
</script>

</body>
</html> 

Console Dot Log Method Demo

Printing HTML Pages with JavaScript

JavaScript provides a simple way to print the content of a webpage using the window.print() method. This method opens the browser's print dialog, allowing users to print the current page or specific content displayed in the browser window.

<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this document</button>

</body>
</html>

Questions & Answers