- innerHTML will write output in HTML element
- document.write() will write into HTML output
- window.alert() will show output in alert box
- console.log() will write output in browser console.
Let's look at those 4 ways one by one.
This is the most common method of displaying data (output).
To access the HTML element we use document.getElementById (name of the id in html) method. We assign 'id' to HTML element and innerHTML is the content of that element.
Take a look at the example below.
.innerHTML Example/* Outptut */ innerHTML example
Checkout the examples in the DEMO Link.
The problem with document.write is that if you call it after the document is loaded, then it'll delete all the existing HTML code and write the new one with the new output.
We can use alert box to display output but it's not useful in all situations. It's really useful for warnings only. For e.g. if user enters text instead of number. Take a look at the example below...
It will give you an alert when you click on the button.
We use console.log() mostly for debugging purposes only. You really can't see the output on your browser screen. Take a look...