Are you

JavaScript Output


JavaScript Display Possibilities

  • Writing something into the HTML output using document.write().
  • Writing something into an HTML element, using innerHTML.
  • Writing something into the browser console, using console.log().
  • Writing something into an alert box, using window.alert().

Therefore, let's discuss each and every one of them.

How to Write into an HTML Element Using innerHTML?

When access an HTML element, JavaScript can use the document.getElementById(id) method.

The HTML element is defined by its id attribute. The innerHTML property specifies the HTML content:

Example

<!DOCTYPE>
<html>
<body>
<h1>
JavaScript Example
</h1>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Output

JavaScript tutorial example - JavaScript language

In the above example, we check the HTML element with "id=demo" and change its content to 11.

Note: Changing an HTML element's innerHTML property is a common way to display data in HTML.

How to Write into an alert box Using window.alert()?

An alert box can be used to display data as shown in example below:

<!DOCTYPE>
<html>
<body>
<h1>
JavaScript Example for window.alert()
</h1>
<p id="demo"></p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

Output

JavaScript example - JavaScript language

In JavaScript, the window object is the global scope object, that means that variables, properties, and methods by default belong to the window object. This also implies that specifying the window keyword is optional

You can omit the window keyword:

<!DOCTYPE>
<html>
<body>
<h1>
JavaScript Example for alert()
</h1>
<p id="demo"></p>
<script>
alert(5 + 6);
</script>
</body>
</html>

Output

JavaScript example - JavaScript language

How to Write into the HTML output Using document.write()?

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

<!DOCTYPE>
<html>
<body>
<h1> JavaScript Example for document.write()</h1>
<p id="demo"></p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Output

JavaScript example - JavaScript language

The document.write() method should only be used for testing.

Note: Using document.write() after an HTML document is loaded, will delete all existing HTML

How to Write into the browser console Using console.log()?

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

Example

<!DOCTYPE>
<html>
<body>
<h1>
JavaScript Example for console.log()
</h1>
<p id="demo"></p>
<script>
console.log(5 + 6);
</script>
</body>
</html>

Output

JavaScript example - JavaScript language

JavaScript Print

There are no print objects or methods in JavaScript.

JavaScript does not have access to output devices.

The only exception is that you can call the window.print() method in the browser to print the content of the current window.

Next

Courses