JavaScript is a popular programming language used for web development. Here's how to create a simple "Hello World" program in JavaScript.
Create an HTML File
First, create an HTML file. This file will contain the structure of your webpage and run the JavaScript code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello World in JavaScript</title> </head> <body> <h1>Welcome to JavaScript!</h1> <p id="greeting"></p> <script> // Your JavaScript code will go here document.getElementById("greeting").innerText = "Hello World!"; </script> </body> </html>
Add JavaScript Code
Inside the <script>
tag, you can write JavaScript. In this case, the code changes the text of a paragraph with the id="greeting"
to "Hello World!"
.
document.getElementById("greeting").innerText = "Hello World!";
This line of code accesses the HTML element with the ID greeting and changes its text content to "Hello World!"
.
Open the HTML File
Once you’ve saved the file with a .html extension, open it in a web browser. You’ll see the page display "Welcome to JavaScript!" and "Hello World!" in the paragraph below it.
-
document.getElementById("greeting")
: This method finds the element with the IDgreeting
in the HTML. -
innerText = "Hello World!"
: This sets the content of the selected element to "Hello World!".
You find the fill example in codepen
Conclusion
This is the simplest way to write JavaScript that interacts with an HTML page. You can use this basic setup to start exploring JavaScript further and adding more functionality to your web pages.
Top comments (1)
Here is the full example at CodePen