How to Link JavaScript to HTML: Simple Methods Explained
You link JavaScript to HTML by using the
<script> tag inside your HTML file. You can place JavaScript code directly inside this tag or link an external JavaScript file using the src attribute.Syntax
The <script> tag is used to add JavaScript to an HTML page. You can write JavaScript code inside the tag or link an external file using the src attribute.
- <script> ... </script>: Place JavaScript code directly inside.
- <script src="file.js"></script>: Link an external JavaScript file.
- The
srcattribute must point to the correct file path. - Place the
<script>tag in the<head>or just before</body>for better loading.
html
<!-- Inline JavaScript --> <script> console.log('Hello from inline script!'); </script> <!-- External JavaScript --> <script src="script.js"></script>
Example
This example shows how to link an external JavaScript file to an HTML page and run a simple function that changes the text on the page when a button is clicked.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Link JS Example</title> <script src="script.js"></script> </head> <body> <h1 id="greeting">Hello!</h1> <button onclick="changeText()">Click me</button> </body> </html> // script.js function changeText() { document.getElementById('greeting').textContent = 'You clicked the button!'; }
Output
When the button is clicked, the text 'Hello!' changes to 'You clicked the button!'
Common Pitfalls
Common mistakes when linking JavaScript to HTML include:
- Forgetting to include the
srcattribute when linking external files. - Placing the
<script>tag before the HTML elements it tries to access, causing errors. - Using incorrect file paths in the
srcattribute. - Not closing the
<script>tag properly.
html
<!-- Wrong: script before element --> <script src="script.js"></script> <h1 id="greeting">Hello!</h1> <!-- Right: script after element --> <h1 id="greeting">Hello!</h1> <script src="script.js"></script>
Quick Reference
| Method | Usage | Notes |
|---|---|---|
| Inline Script | Good for small scripts inside HTML | |
| External File | Keeps code separate and reusable | |
| Placement | In or before | Placing before |