Methods to Display Output

Before going to details about JavaScript, lets first see how we can display data in JavaScript. Their are various ways to display data in JavaScript. Some of them are :

1. By using innerHTML :

innerHTML is a DOM property to insert content to a specified id of an element. To access an HTML element, Javascript can use document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content. So with
  document.getElementById(id).innerHTML
We can change the innerHTML property. For example :
<!DOCTYPE html>
<html>
<body>
  <p id="demo"></p>
  <script>
    document.getElementById("demo").innerHTML = "Hello world. This is innerHTML";
  </script>
</body>
</html>
Output :

Hello world. This is innerHTML


2. By document.write Method :

The write() method writes HTML expressions or JavaScript code to a document. The document.writeln() method is similar to write(), only it adds a newline character after each statement. The document.write() method is mostly used for testing. For example :
<!DOCTYPE html>
<html>
<body>
  <script>
    document.write("Hello world. This is innerHTML");
  </script>
</body>
</html>
Output :

Hello world. This is innerHTML


3. With alert() or prompt() :

The alert() method displays an alert box with a specified message and an OK button. For example :
<html>
<head>
  <script>
    function hello() {
      alert("Hello world From mycsnotes.com");
    }
  </script>
</head>
<body>
  <input type="button" onclick="hello()" value="Click Here" />
</body>
</html>
Output :


The prompt() method displays a dialog box that prompts the visitor for input. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. For example :
<html>
<head>
  <script>
    function hello() {
    prompt("Hello world From mycsnotes.com");
    }
  </script>
</head>
<body>
  <input type="button" onclick="hello()" value="Click Here" />
</body>
</html>
Output :



4. With console.log()

The console.log() method writes a message to the console. For debugging purposes, you can use the console.log() method to display data. Example :
<html>
<body>
  <script>
    console.log("Hello world!!");
    console.log("This is console.log test.");
  </script>
</body>
</html>
Output :


To see the console log, right click on the browser window and click on "inspect" option.

Next Topic :