Output elements in javascript

Different possibilities to get the output of javascript code. These are

  1. Using console.log(), write into the browser console and get the output. 
  2. Using window.alert(), write the message to the alert box window and get the output. 
  3. Using innerHTML or document.write(), writing the output into the HTML page using id or name attributes.

Display data using innerHTML Method

We can use the javascript tag document.getElementById('yourID') method to access an HTML element using JavaScript. The attribute id defines in the HTML tag where as innerHTML property defines the HTML content.

Try this Example Now

<!DOCTYPE html>
<body> 
<p id="myoutput"></p> 
<script> 
document.getElementById("myoutput").innerHTML = 10 + 2; 
</script> 
</body> 
</html>

Display data using document.write() Method 

This method document.write() is only used for testing purposes. We can use it directly to onclick event in HTML or use in the script tag. 

Example: TRY THIS EXAMPLE NOW

Try this Example Now

<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="document.write(10 + 8)">Click to see output</button>
</body>
</html>

Try this Example Now

<!DOCTYPE html>
<html>
<body>
<script>
  document.write(5 + 6);
</script>
</body>
</html>

Output Using window.alert() Method

You can use an alert box to display data of your javascript code. You can skip the window keyword. This means window keyword is optional while writing a javascript code. 

Try this Example Now

<!DOCTYPE html>
<html>
<body>
<script>
window.alert(10 + 2);
alert(10 + 2);
</script>
</body>
</html>

Output Using console.log() method

You can call the console.log() method in the browser to display data. it is only use for debugging the javascript code.

Try this Example Now

<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>

Advantages Of NCERT, CBSE & State Boards Solutions For All Subjects

  • All the NCERT Solutions have been prepared by academic experts having 10+ years of teaching experience.
  • They have prepared all the solutions in simple and easy language, so that each and every student can understand the concepts easily.
  • All the solutions have been explained step to step wise in details with better explainations.
  • Students can also use these question and answers for your assignments and in homework help.
  • All the solutions have been explained in detail and the answers have been compiled in a step-wise manner.
  • All the question and asnwers are commonly prepared according to the Latest Syllabus of Board Education and Guidelines.
  • Students can know about the various types of questions asked in the exams with the help of these solutions.

Top Engineering Courses