JavaScript Output Statements | How to Display Output

With JavaScript, we can output/write a data in following places:

  • HTML element
  • HTML output
  • Alert box
  • Browser console

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 above example, the document.getElementById("val") returns an HTML element whose ID value is val, from current HTML document.

Note - The innerHTML sets/returns the content to/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 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 same class name, therefore the method returns collection of elements. That is why, we need to process in array-way 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>
Output

Write Data into an Alert Box using JavaScript

To write into an alert box, we need to use window.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/message 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>

Note - To learn in detail about console.log(), refer to its separate tutorial.

JavaScript Online Test


« Previous Tutorial Next Tutorial »