html
  1. html-script-tag

HTML <script> Tag

  • The HTML <script> tag is used to define a client-side script.
  • It can be used to define a JavaScript function or an external JavaScript file to be included in the HTML document.

Syntax

The basic syntax for the HTML <script> tag is as follows:

<script>
  // JavaScript code here
</script>

The <script> tag can be included in the <head> or <body> section of an HTML document. Additionally, it can also include a src attribute which can be used to link to an external JavaScript file.

<script src="path/to/script.js"></script>

Example

Here is an example of how to use the <script> tag inline in an HTML document:

<!DOCTYPE html>
<html>
  <head>
    <title>Example Document</title>
  </head>
  <body>
    <h1>Hello World</h1>
    <script>
      alert("This is an example alert!");
    </script>
  </body>
</html>
Try Playground

When the example above runs, it displays an alert with the message "This is an example alert!".

Explanation

The <script> tag is used to define JavaScript code to be executed by the browser. This code can be included directly in the HTML document using the inline syntax, or it can be included in an external file by using the src attribute.

Use

The <script> tag can be used to perform a wide range of actions, including:

  • Collecting user input
  • Validating form data
  • Animating elements
  • Displaying alerts and notifications
  • And much more

Important Points

  • The <script> tag must be included in the <head> or <body> section of an HTML document.
  • Inline JavaScript code must be contained within the <script> tags.
  • The src attribute can be used to link to an external JavaScript file.
  • Multiple <script> tags can be included in an HTML document to define multiple scripts.

Summary

The HTML <script> tag is a powerful tool for defining client-side scripts in an HTML document. It can be used to define JavaScript functions that can be executed on user input, validate form data, and much more. With its inline and external file syntax options, it provides flexibility for developers to include scripts directly in the document or link to external files.

Published on: