Table of Contents
Display Output using JavaScript
To display anything on our screen, we were earlier using HTML or XML and even CSS. Now, we can also use JavaScript to display output in our website. JavaScript helps us to display dynamic output i.e. output is not static and can be changed according to the requirement at runtime. For example, we can take two numbers as input and display their sum using JavaScript.
Following are the different JavaScript based output possibilities:
- Writing into an HTML element [using innerHTML]
In HTML & CSS section, we have discussed how to access an HTML element using its id. Now, we will use the same id to display our output within that element. Syntax is shown below:
document.getElementById("<your_element_name>").innerHTML
You will better understand this concept from given example. For given HTML code, the output is shown just below to it:
Output:
Now, there is a requirement to change “The God of Cricket” to “The Lord of Cricket”. In this case, we will access this element via its id that is “idH2” (as per the code shown above). Let us directly code in the browser console and check the output there itself.
In the first line, we have checked what is the value of HTML for element “idH2”. In the second line, we have replaced the earlier value with our required value. The new output is shown below:
- Writing into the HTML output [using document.write()]
This statement is used mainly for test purpose as it removes all the existing HTML with the given value. The syntax is given below:
document.write(“<your_text>”):
We have used above syntax to print a static statement below:
- Writing into an alert box [using window.alert()]
Many times, there is a requirement to print a message as an information for a user to alert him. This is where alert box comes into the picture. The syntax is as shown below:
windows.alert("<your_alert_text");
- Writing into the browser console [using console.log()] This is the most preferred way to check the output while debugging your JavaScript code. We will show its use while discussing the debugger section.
Console.log("<your_output_text");
0 Comments