JavaScript Output Statements: How to Display Output

With JavaScript, we can output or write data in the following places:

Write data into an HTML element using JavaScript

To write or output data into an HTML element, we need to use the innerHTML property. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>The value is <span id="val"></span>.</p>
   
   <script>
      document.getElementById("val").innerHTML = 10;
   </script>
   
</body>
</html>
Output

The value is .

In the above example, document.getElementById("val") returns an HTML element whose ID value is val from the current HTML document.

Note: The innerHTML sets or returns the content of an HTML element.

To write data into an HTML element using JavaScript innerHTML, first we need to get the HTML element using any of the following methods:

Here is another example of writing data into an HTML element using the JavaScript getElementsByClassName() method.

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>The value is <span class="x"></span>.</p>
   <p>The value is <span class="x"></span>.</p>
   <p>The value is <span class="x"></span>.</p>
   
   <script>
      var elements = document.getElementsByClassName("x");
      var totElements = elements.length;
      
      for(var i=0; i<totElements; i++)
      {
         elements[i].innerHTML = 10;
      }
   </script>
   
</body>
</html>
Output

The value is .

The value is .

The value is .

Since multiple elements can have the same class name, the method returns a collection of elements. That is why we need to process in an array-like manner to write data into all returned elements, one by one.

Write data into HTML output using JavaScript

To write directly into HTML output, we need to use the document.write() method. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <script>
      document.write("Hi there!");
   </script>
   
</body>
</html>

The output produced by the above example is shown in the snapshot given below:

javascript display output example

Write data into an alert box using JavaScript

To write into an alert box, we need to use alert() method. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <button onclick="myFunction()">Click Me to Alert</button>
   <script>
      function myFunction() {
         alert("Hi there!");
      }
   </script>
   
</body>
</html>
Output

Write data into the web console using JavaScript

To write data or messages into the browser or web console, we need to use the console.log() method. For example:

<!DOCTYPE html>
<html>
<body>

   <script>
      console.log("Hello there!");
   </script>
   
</body>
</html>

The output of this example should be:

javascript output example

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!