innerHTMLproperty– to write inside an HTML element
alert()method– to create an alert box
document.write()method– use to output in HTML. Just for testing purposes, not recommended
console.log()– for debugging
1. Use innerHTML Property
This innerHTML method is used to print inside HTML elements. By using this method, you can print Hello World inside the HTML elements. We use it with the getElementsById() method.
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=, initial-scale=1.0"> <title>A Simple Js Program</title> </head> <body> <h2 id="demo"></h2> <script> document.getElementById('demo').innerHTML = "Hello World!"; </script> </body> </html>
In the above code, I print ‘Hello World’ in the h2 element. To do this first I specified the id attribute for the h2 element so that I can access this element through the document.getElementById method. The ‘Hello World’ is enclosed in pair of double quotes because it is a text string. And it is the visible part that you will see in your browser.
However, you can use both double or single quotes. Inside the parenthesis or round brackets, I used the name of the id which is ‘demo‘ to write a text string inside the h2 element.
After the execution of the code, the output will look similar to the one below.
Let’s see the second method.
2. Use alert() Method to Print Hello World
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=, initial-scale=1.0"> <title>A Simple Js Program</title> </head> <body> <script> alert("Hello World!"); </script> </body> </html>
<script> tags are not necessary.
3. Use the document.write() Method
This method is for testing purposes we don’t use it regularly and it is not recommended. The document.write() method directly prints in the body of HTML. Just see lines no. 11 to 13 in the code example below.
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=, initial-scale=1.0"> <title>A Simple Js Program</title> </head> <body> <script> document.write("Hello World!"); </script> </body> </html>
Let’s see the last method.
4. Use console.log() Method
Firstly, you need to open your browser’s console. To do this, open a new tab in your browser. Then, right-click and click inspect as shown below.
After that click on the console, and write your code there as shown below.
You can copy this line of code and paste it into your browser’s console. Then, click enter and you will see the result is the same as shown below.
That’s it. Hope you liked it. If you have any questions related to this tutorial then feel free to ask in the comments section below.
Don’t forget to help others by sharing this tutorial!