How to print messages on browser using javascript?
JavaScript Output
In JavaScript there are several different ways of generating output including writing output to the browser window or browser console, displaying output in dialog boxes, writing output into an HTML element, etc.
Output to Browser Console
You can easily outputs a message or writes data to the browser console using the console.log() method.
File name : index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Writing into the Browser's Console with JavaScript</title>
</head>
<body>
<script>
console.log("Hello World!");
// Printing a variable value
var x = 10;
var y = 20;
var sum = x + y;
console.log(sum); // Prints: 30
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
</body>
</html>
Alert Dialog Boxes
alert dialog boxes to display the message or output data to the user. An alert dialog box is created using the alert() method.
File name : index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Writing into an Alert Dialog Box with JavaScript</title>
</head>
<body>
<script>
// Displaying a simple text message
alert("Hello World!"); // Outputs: Hello World!
// Displaying a variable value
var x = 10;
var y = 20;
var sum = x + y;
alert(sum); // Outputs: 30
</script>
</body>
</html>
Browser Window
You can use the document.write() method to write the content to the current document only while that document is being parsed.
File name : index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Writing into an Browser Window with JavaScript</title>
</head>
<body>
<script>
// Printing a simple text message
document.write("Hello World!"); // Prints: Hello World!
// Printing a variable value
var x = 10;
var y = 20;
var sum = x + y;
document.write(sum); // Prints: 30
</script>
</body>
</html>
If you use the document.write() method method after the page has been loaded, it will overwrite all the existing content in that document.
File name : index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Problem with JavaScript Document.write() Method</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
<button type="button" onclick="document.write('Hello World!')">Click Me</button>
</body>
</html>
Inside an HTML Element
write or insert output inside an HTML element using the element's innerHTML property.
File name : index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Writing into an HTML Element with JavaScript</title>
</head>
<body>
<p id="greet"></p>
<p id="result"></p>
<script>
// Writing text string inside an element
document.getElementById("greet").innerHTML = "Hello World!";
// Writing a variable value inside an element
var x = 10;
var y = 20;
var sum = x + y;
document.getElementById("result").innerHTML = sum;
</script>
</body>
</html>
Previous
Next