How to Use JavaScript in HTML

Beginner
12 min read
Updated: Nov 2026
6 examples
<script> / DOM

Definition and Usage

JavaScript in HTML means connecting behavior to your markup with the <script> element. HTML builds structure, CSS styles it, and JavaScript responds to clicks, updates text, and validates forms—without reloading the page.

What does the HTML script element do?

It tells the browser to run JavaScript as part of the document. Code can live inside the tag (inline) or in a separate .js file linked with src.

When should you add scripts to HTML?

Whenever the page needs interactivity: buttons, live text updates, form checks, or talking to APIs. Start with a small inline <script> at the end of <body>, then move logic into external files as the project grows.

HTML vs CSS vs JavaScript

Keep roles clear in your HTML project: markup for content, CSS for presentation, and scripts for behavior. Mixing large scripts into every page makes HTML hard to maintain.

Baseline · Widely available.

Every modern browser includes a JavaScript engine. You do not install plugins to run the HTML examples in this tutorial.

Order in the HTML document matters.

A script that calls getElementById before that element appears in the HTML will fail. Place the script after the markup, or use defer on external files in <head>.

Prefer external .js for real HTML sites.

Inline scripts are great for learning. Reusable behavior belongs in files linked with <script src="app.js"></script>.

HTML Syntax

syntax.html
<script> /* JavaScript */</script>
external.html
<script src=" app.js" defer></script>

Both start and end tags are required. With src, leave the element empty—do not put code between the tags. See the full <script> tag reference for async, type="module", and more.

Core HTML Concepts

Terms you will use when wiring JavaScript into an HTML document:

ConceptMeaning in HTML
<script>HTML element that embeds or loads JavaScript
srcPath to an external .js file
deferRun the external script after HTML parsing finishes
<head> / <body>Where you place scripts in the HTML document
Inline scriptJavaScript written between <script> tags in the HTML file
External scriptSeparate .js file linked from HTML
DOMBrowser’s live tree of the HTML page that scripts can change
onclickHTML event attribute that runs JavaScript on click (fine for demos)

Ways to add JavaScript to HTML

MethodHTML patternBest for
Inline / internal<script>...</script>Learning, small page-specific logic
External<script src="app.js"></script>Real projects and reusable code
Deferred in head<script src="app.js" defer>Keeping scripts in <head> safely

How to Add JavaScript to an HTML Page

Connect a script to your HTML, place it so the DOM is ready, then update elements or handle events.

  1. Create your HTML structure (h1, p, button, etc.) with clear ids when scripts need them.
  2. Add a <script> at the end of <body>, or link <script src="app.js" defer> from <head>.
  3. Select elements with document.getElementById(...) (or query selectors) and change textContent, classes, or styles.
  4. Hook up clicks with a button onclick for demos, or addEventListener in the script for cleaner HTML.
  5. Move repeated logic into an external .js file and keep HTML focused on content.
TaskHTML / script pattern
Inline script<script>/* code */</script> before </body>
External file<script src="app.js" defer></script>
Update textdocument.getElementById('id').textContent = '...'
Click (demo)<button onclick="...">

Live Preview

Pick a message and apply it to a sample HTML paragraph—the same idea as an inline script calling textContent.

Mirrors document.getElementById('status').textContent = '...' in HTML.

Sample HTML element

Hello, JavaScript is working!

Updated #status via script-style textContent

HTML Examples

Six patterns from your first embedded script to a full interactive HTML page. Use Try It Yourself for a live editor.

Example 1 — Embedded Script in HTML

Put JavaScript inside a <script> block so it updates a paragraph when the page loads.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>HTML with JavaScript</title>
</head>
<body>
  <h1>Welcome to My Website</h1>
  <p id="status">Waiting...</p>

  <script>
    document.getElementById('status').textContent =
      'Hello, JavaScript is working!';
  </script>
</body>
</html>
Try It Yourself

How It Works

  1. HTML first. The paragraph with id="status" is in the document before the script.
  2. Script runs when the browser reaches the <script> tag while parsing.
  3. getElementById finds that HTML element in the DOM.
  4. textContent replaces the visible text without reloading the page.

Example 2 — Script at the End of <body>

Place the script after your HTML content so elements exist before the code runs.

HTML
<body>
  <h1>Page Content Loads First</h1>
  <p id="note">This paragraph exists before the script runs.</p>

  <script>
    document.getElementById('note').textContent =
      'Script ran after the HTML was parsed.';
  </script>
</body>
Try It Yourself

How It Works

  1. Body content parses first so the DOM already contains #note.
  2. Bottom placement is the safest default for beginners.
  3. Head without defer can run too early and return null from getElementById.
  4. Alternative: <script src="..." defer> in <head>.

Example 3 — External JavaScript File

Keep HTML clean by linking a separate .js file with src and defer.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>External JavaScript Demo</title>
  <script src="app.js" defer></script>
</head>
<body>
  <h1>External JavaScript File Example</h1>
  <p id="log">Loading script...</p>
</body>
</html>
JS
console.log('This message is from an external JavaScript file.');

var log = document.getElementById('log');
if (log) {
  log.textContent = 'This message is from an external JavaScript file.';
}

How It Works

  1. src points the HTML document at a separate file.
  2. defer waits until HTML parsing finishes, then runs the file.
  3. Empty script element—do not put code between the tags when using src.
  4. Path must match your folder layout relative to the HTML file.

Example 4 — Event Handling from HTML

An HTML button with onclick runs JavaScript when the user clicks.

HTML
<button type="button" onclick="alert('Button clicked!')">Click Me</button>
Try It Yourself

How It Works

  1. HTML event attributes like onclick call JavaScript from markup.
  2. Good for demos; larger HTML apps usually use addEventListener in a script file.
  3. type="button" avoids accidental form submits.
  4. Same idea works for onsubmit, onchange, and other HTML events.

Example 5 — DOM Update from a Button

Change heading text in the live HTML page when a button is pressed.

HTML
<h1 id="myTitle">Original Title</h1>
<button type="button" onclick="updateTitle()">Update Title</button>
<script>
  function updateTitle() {
    document.getElementById('myTitle').textContent = 'New Title';
  }
</script>
Try It Yourself

How It Works

  1. HTML provides the element with a stable id.
  2. onclick calls a function defined in the page script.
  3. getElementById returns the live DOM node.
  4. textContent updates what users see instantly.

Example 6 — Complete Interactive HTML Page

Structure in HTML; behavior in an external complete.js linked with defer.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Example</title>
  <script src="complete.js" defer></script>
</head>
<body>
  <h1>Welcome to JavaScript with HTML</h1>
  <p id="demo">JavaScript can change this text.</p>
  <button type="button" onclick="changeText()">Click me</button>
</body>
</html>
JS
function changeText() {
  var demo = document.getElementById('demo');
  if (demo) {
    demo.textContent = 'Text changed by JavaScript!';
  }
}

How It Works

  1. HTML holds content and a button that names the function to call.
  2. complete.js defines changeText outside the HTML file.
  3. defer ensures the script runs after the HTML is ready.
  4. Separation of concerns: markup vs behavior—easier to reuse and test.

Edge Cases & Pitfalls

Most HTML + JavaScript bugs are placement, wrong paths, or mixing code into src scripts.

null

Script runs before the HTML element exists

getElementById returns null. Move the script below the markup or use defer.

src

Code between tags ignored when src is set

With <script src="...">, leave the element empty. Inline code next to src is not executed.

path

Broken script src path

Check the Network tab. The HTML file’s folder must resolve app.js correctly.

inline

Huge scripts inside every HTML page

Move shared logic to external files so HTML stays readable and cacheable.

valid

Trusting only client-side form checks

HTML + JS validation improves UX, but always validate again on the server.

csp

Inline handlers blocked by CSP

Strict Content-Security-Policy setups may block onclick. Prefer external scripts and addEventListener.

Browser Support

The HTML <script> element, src, defer, and core DOM APIs like getElementById are supported in every modern browser.

✓ Baseline · Since HTML4

script in HTML

All browsers ship a JavaScript engine. The HTML techniques in this tutorial work in Chrome, Firefox, Safari, Edge, and mobile browsers without plugins.

100% Core script support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
<script> & DOM APIs Universal

Bottom line: Write standard HTML and JavaScript—it runs everywhere your users browse.

Key Takeaways

  • HTML hook: add behavior with <script> (inline or src).
  • Placement: end of <body>, or defer in <head>.
  • External files keep HTML clean and reusable across pages.
  • DOM + events: update HTML live; use onclick for demos, listeners for apps.

One line: HTML structure first → <script> after content (or defer) → change the DOM / handle events.

Frequently Asked Questions

Use the HTML script element. Put code between <script> and </script> for inline JavaScript, or link a .js file with <script src="app.js"></script>. The browser downloads and runs it as part of the HTML document.
For beginners, place scripts at the end of body so HTML elements exist before the script runs. Scripts in head run early and may fail if they query elements that are not parsed yet. A modern pattern is <script src="app.js" defer> in head.
Inline JavaScript lives inside the HTML file in a script block. External JavaScript is a separate .js file linked with the src attribute on script. External files keep HTML cleaner and can be reused across pages.
The Document Object Model is the browser’s live tree of your HTML. JavaScript can read and change it—update text, toggle classes, show or hide elements—without reloading the page.
onclick is fine for learning and tiny demos. Production HTML usually keeps markup clean and attaches listeners with addEventListener in a script block or external file.
Not for basic pages—open the .html file in a browser. Some features (modules, fetching local files) need a local server, but the examples in this tutorial work from a normal HTML file.

Make your first HTML page interactive

Open the Try It editor, add a <script> block, and watch the preview respond.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful