DEV Community

Sampson Ovuoba for Devwares

Posted on • Originally published at devwares.com on

Tutorial: Javascript Data Output

Ways JavaScript output can be displayed

Data can be "displayed" in a variety of ways using

  • Using innerHTML to write into an HTML element.
  • Using () to write into the HTML output.
  • Using window.alert to write into an alert box ().
  • Using the browser console to write into

Using innerHTML The document.getElementById(id) method in JavaScript can be used to get an HTML element. The HTML element is identified by its id attribute. The HTML content is specified via the innerHTML property:

Code:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo">Happy coding</p>

<script>
document.getElementById("demo").innerHTML = congratulations on your first JavaScript code;
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In JavaScript, this is a popular method of displaying data.

Using document.write()

It is more convenient to use document.write() for testing purposes.

Code:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Using document.write() after the HTML has been loaded will remove the previous HTML. It should be reserved for testing purposes only.

Using window.alert() :An alert box can be used to present data:

Code:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

You can omit the window keyword.

The window object is the global scope object in JavaScript, which means that variables, attributes, and methods belong to it by default. This also implies that supplying the window keyword is optional. As a result, you can only use the keyword alert.

Code:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Using console.log() :To display data for debugging purposes, use the console.log() method in the browser.

Code:

<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

JavaScript Print: There is no print object or print methods in JavaScript. JavaScript does not support access to output devices. The sole exception is that you can call the window. print() method in the browser to print the contents of the current window.

Code:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Contrast Bootstrap UI Kit

Resources

You may find the following resources useful:

Top comments (0)