JavaScript Various Output (Displaying Data)
In JavaScript, you can display data to the users using various "output" method
provided according to your needs i.e. in a browser dialog box, in the HTML
page etc.
Below are some of the commonly used ways in which data can be displayed to the
user:
innerHTML
: used to write in an HTML Element.-
document.write()
: used to write in the HTML webpage at the place, where it is used. i.e. if it is used in the<head>
tag, then it will write the HTML code in the<head>
tag. -
window.alert()
: used to display browser dialog box, with prespecified text in thealert('your text to show')
method.
-
console.log()
: used to write in the browser console.
Press "ctrl+shift+i" to open developer view and then click console in chrome browser, to view browser console.
Using innerHTML
The innerHTML
is a commonly used property of JavaScript that
changes or add the HTML Content to any HTML Element.
We used document.getElementById('id')
method of JavaScript to
find the element in the HTML document with the defined "id". The
id is unique along the whole web page. There are also several
other methods for getting reference to any HTML element. We will know about it
later.
Below is the example code given which shows how to use
innerHTML
property of JavaScript.
<!-- Adding HTML Content -->
using document.write()
The document.write()
method of JavaScript adds the HTML content
at the place, where it is used i.e. If it is used in
<head>
element, then the HTML Content gets added to
<head>
.
This is generally used for testing purposes.
*Using it after the page load completes will replace all the existing HTML Content.
Below is the example, which shows the use of document.write()
for
testing purposes.
Below is the example, which shows the use of
document.write()
after the page finished loading.
using window.alert()
The window.alert("text")
method of JavaScript displays the
browser's dialog box with "text" in the alert()
method.
This method can skip the window
keyword i.e. we can directly use
method as alert("text")
.
The window
object is the global scope object, and all the
variables, properties, methods are by default referenced to it. This means, we
can skip this keyword.
Below is the example which shows the use of
window.alert("text")
method.
Below is the example which shows the use of alert("text")
method
(without using the window keyword).
using console.log()
The console.log()
method of JavaScript is used for debugging
purposes i.e. checking the proper functioning of the JavaScript code.
The browser console can be accessed with "ctrl+shift+i" and then click console in the chrome browser.
Below is the example for using console.log()
method of
JavaScript.
using window.print()
The window.print()
method of JavaScript is an exception and is
used to print the current page in the browser.
Below is the example for using window.print()
.
Comments
Post a Comment