- Writing into an HTML element, using innerHTML.
- Writing into the HTML output using document.write().
- Writing into an alert box, using window.alert().
- Writing into the browser console, using console.log().
Writing Output to Browser Console
You can easily output a message or writes data to the browser console using the console.log() method. This method is very simple yet very powerful method for generating detailed output. Here’s an example:
<!DOCTYPE html> <html> <body> console.log("Hello India!"); var x = 10; var y = 20; var sum = x + y; console.log(sum); </body> </html>
NOTE: To access your web browser’s console, first press the F12 key on the keyboard to open the developer tools then click on the console tab.
Displaying Output in Alert Dialog Boxes
<!DOCTYPE html> <html> <body> window.alert("Hello India!"); var x = 10; var y = 15; var sum = x + y; alert(sum); </body> </html>
Writing Output to the Browser Window
You can use the document.write() method to write the content to the current document only while that document is being parsed
<!DOCTYPE html> <html> <body> document.write("Hello India!"); var x = 10; var y = 20; var sum = x + y; document.write(sum); </body> </html>
If you use the document.write() method after the page has been loaded, it will overwrite all the existing content in that document. Check out the following example:
<!DOCTYPE html> <html> <body> <h1>This is a heading</h1> <p>This is a paragraph of text.</p> <button type="button" onclick="document.write('Hello India!')">Click Me</button> </body> </html>
innerHTML –Inserting Output Inside an HTML Element
Understanding innerHTML First
The innerHTML can load a specific page content without refreshing the whole page. This reduces the data usages and the time to load a page. This gives a much fast and responsive feel and hence making the user experience much better.
innerHTML is used in the web pages to generate dynamic HTML such as registration form, comment form, links, etc.
The element’s innerHTML property is used to write or insert output inside an HTML element. Before writing the output, we need to select the element using a method getElementById(), as shown below :
<!DOCTYPE html> <html> <body> <p id="greet"></p> <p id="result"></p> <script> // Writing text string inside an element document.getElementById("greet").innerHTML = "Hello India!"; // 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>
The innerHTML summary:
- The innerHTML property of an element is used to get or set the values of HTML contained within the element.
- The innerHTML property returns the current HTML source of the element, including any change that has been made since the page was loaded.
- Avoid using innerHTML to set new content that you don’t have control to avoid a security risk.
<!DOCTYPE html> <html> <body> <button onclick="window.print()">Print this page</button> </body> </html>