HTML and JavaScript are two separate technologies, but they can be used together to create dynamic and interactive web pages.
To add JavaScript to an HTML page, you can use the <script>
element. The <script>
element can be placed in the <head>
section or the <body>
section of an HTML page.
Here’s an example of how to add JavaScript code to an HTML page using the <script>
element:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
<script>
// JavaScript code goes here
alert("Hello, world!");
</script>
</head>
<body>
<h1>Welcome to my page</h1>
<p>This is some text on my page</p>
</body>
</html>
In this example, the JavaScript code is contained within a <script>
element in the <head>
section of the page. The JavaScript code simply displays an alert message when the page is loaded.
You can also link to an external JavaScript file using the src
attribute of the <script>
element. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
<script src="myscript.js"></script>
</head>
<body>
<h1>Welcome to my page</h1>
<p>This is some text on my page</p>
</body>
</html>
In this example, the JavaScript code is contained in an external file called “myscript.js”. The src
attribute of the <script>
element is used to link to the external file.
The “myscript.js” file might contain code like this:
alert("Hello, world!");
When the page loads, the JavaScript code in “myscript.js” will be executed, and an alert message will be displayed.
There are many other ways to use JavaScript with HTML, including event handling, form validation, and dynamic content creation.