EthicsComputerCourses
Join training +91 90532 10052

HTML Integration with JavaScript

HTML · Lesson 77 of 234 Intermediate 9 min read Updated

By the end of this lesson you will be able to attach a script to a page in the right place, find elements, react to clicks and form submissions, and show the user's data on the page safely.

HTML gives a page its structure and HTML Integration with CSS gives it a look. JavaScript gives it behaviour: it can read the page, change it and respond to the user. Think of a cricket ground. HTML is the field and the stands, CSS is the paint and the flags, and JavaScript is the scoreboard operator who updates the board after every ball.

Where the script element goes

You connect a script with the <script> element. Like CSS, it belongs in a separate file, such as js/app.js, that every page can share.

HTML
<head>
  <meta charset="utf-8">
  <title>Rohtak Rasoi</title>
  <link rel="stylesheet" href="css/style.css">
  <script src="js/app.js" defer></script>
</head>

The defer attribute is the important part. A plain <script> stops the browser from reading the HTML until the script has downloaded and run. With defer, the file downloads alongside the HTML and runs only after the whole page has been read, so your script can find every element.

You have three good choices:

  • defer for your own classic scripts, placed in the head.
  • type="module" for modern code that uses import and export. Modules are deferred automatically.
  • async for independent scripts, such as analytics, that do not touch your page.

The timing table and a live demo are in Loading & Performance Hints, and Script Loading: Async & Defer goes deeper later.

Selecting elements

Before a script can change an element, it must find it. The browser offers the page as the DOM, a tree of objects whose root is document.

MethodReturns
document.querySelector("#total")The first element matching a CSS selector, or null
document.querySelectorAll(".item")A list of every matching element
document.getElementById("total")The element with that id, or null

querySelector accepts any CSS selector you already know: #id, .class, form input[type="email"]. The JavaScript course covers selection in depth in The DOM: Selecting Elements.

Events with addEventListener

An event is something that happens on the page: a click, a key press, a form submit, a change in a text box. You run code when an event happens by adding a listener, a function the browser calls for you.

JavaScript
const button = document.querySelector("#add");
button.addEventListener("click", () => {
  console.log("Samosa added to the order");
});

Always attach listeners in your script file with addEventListener. You will often see the older style, an onclick attribute written inside the HTML, such as <button onclick="addItem()">. Avoid it for three reasons:

  1. It mixes behaviour into your markup, so HTML and JavaScript are harder to change separately.
  2. An element can hold only one onclick value, but many listeners.
  3. A Content Security Policy, a common security header, usually blocks inline handlers, so they stop working. See Content Security Policy (CSP).

textContent or innerHTML?

There are two common ways to put text into an element:

  • element.textContent = value treats the value as plain text. Any < or > characters appear as they are.
  • element.innerHTML = value treats the value as HTML. The browser parses it and builds new elements.

Use textContent for anything a user typed or any data from a server. With innerHTML, someone can type HTML that runs code on your page. This attack is called cross-site scripting (XSS). Run the example and compare the two lines.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>textContent vs innerHTML</title>
</head>
<body>
  <label for="name">Your name</label>
  <input id="name" value="<b>Priya</b>">
  <button id="greet">Greet</button>
  <p>textContent: <span id="safe"></span></p>
  <p>innerHTML: <span id="unsafe"></span></p>

  <script>
    document.querySelector("#greet").addEventListener("click", () => {
      const name = document.querySelector("#name").value;
      document.querySelector("#safe").textContent = "Welcome, " + name;
      document.querySelector("#unsafe").innerHTML = "Welcome, " + name;
    });
  </script>
</body>
</html>

The first line shows the tags as plain characters. The second turns them into real bold text. Bold is harmless, but an attacker could type an image tag with code in an error handler instead. You will learn defences in Cross-Site Scripting (XSS) Prevention.

From a form to the page

Here is the data flow you will build again and again: the user fills a form, your script reads it, and the page updates. Let us build a hostel mess expense list for Farhan in Lucknow, step by step.

  1. Step 1: write a normal form with labels and name attributes. You should see two fields and a button.
  2. Step 2: listen for the form's submit event, not the button's click, so pressing Enter works too.
  3. Step 3: call event.preventDefault() to stop the browser loading a new page.
  4. Step 4: read the values with new FormData(form), which collects every field by its name.
  5. Step 5: create a new <li>, fill it with textContent and add it to the list. You should see the item appear.
  6. Step 6: reset the form and move focus back to the first field for the next entry.
HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Mess Expenses</title>
</head>
<body>
  <h1>Farhan's mess expenses</h1>
  <form id="expense-form" action="/expenses" method="post">
    <label for="item">Item</label>
    <input id="item" name="item" required>
    <label for="amount">Amount (₹)</label>
    <input id="amount" name="amount" type="number" min="1" required>
    <button>Add</button>
  </form>
  <ul id="list"></ul>
  <p>Total: ₹<output id="total">0</output></p>

  <script>
    const form = document.querySelector("#expense-form");
    let total = 0;

    form.addEventListener("submit", (event) => {
      event.preventDefault();
      const data = new FormData(form);
      const amount = Number(data.get("amount"));

      const li = document.createElement("li");
      li.textContent = data.get("item") + ": ₹" + amount;
      document.querySelector("#list").append(li);

      total += amount;
      document.querySelector("#total").textContent = total;
      form.reset();
      document.querySelector("#item").focus();
    });
  </script>
</body>
</html>

Notice that the required and min attributes still work. The browser checks them before the submit event fires, so your script only receives valid data. The form also keeps a real action, so it could still send data to a server without the script.

noscript

The <noscript> element holds content shown only when scripting is turned off or blocked. In the body it can hold any normal content. In the head it may contain only <link>, <style> and <meta> elements.

HTML
<noscript>
  <p>The live price calculator needs JavaScript. You can still <a href="/price-list.pdf">download the price list</a>.</p>
</noscript>

It is a small safety net, not a plan. Better still, make the core task work without JavaScript and improve it with a script: Progressive Enhancement.

Common mistakes

  • A plain script in the head. It runs before the body exists and finds null. Add defer.
  • Inline onclick attributes. Use addEventListener in the script file.
  • innerHTML with user input. Use textContent, or create elements.
  • Listening to the button's click instead of the form's submit. Enter-key submissions and validation get skipped.
  • Forgetting preventDefault(). The page reloads and your update disappears.

Interview questions

1. What is the difference between defer and async?

Both download the script without blocking the HTML parser. Deferred scripts run after parsing finishes, in the order they appear. Async scripts run as soon as they arrive, in any order, so they suit independent code.

2. Why prefer addEventListener over an onclick attribute?

It keeps behaviour out of the markup, allows several listeners on one element, and works under a Content Security Policy that blocks inline handlers. Listeners can also be removed with removeEventListener.

3. When is innerHTML dangerous?

When the string contains anything from a user or an outside source. The browser parses it as HTML, so an attacker can inject elements that run code, which is cross-site scripting. textContent inserts plain text and avoids this.

4. Why listen to the form's submit event instead of the button's click?

The submit event fires for every way of submitting, including the Enter key, and only after built-in validation passes. A click handler on the button misses those cases.

5. What does FormData do?

It collects the current values of all named controls in a form into an object you can read with get(). You can also send it directly with fetch.

Key points

  • Load scripts from a file in the head with defer or type="module"; use async only for independent scripts.
  • Find elements with querySelector, querySelectorAll and getElementById.
  • Attach behaviour with addEventListener, not onclick attributes.
  • Use textContent for text and keep innerHTML away from user input.
  • Handle forms on submit, call preventDefault(), read with FormData, then update the page.
  • Use <noscript> as a small fallback, and build the core task to work without scripts.

Exercise

Build a "Train ticket enquiry" page for Isha. The form has a labelled "From" station, a "To" station and a passenger count (number, 1 to 6). On submit, without reloading, add a line such as "Jaipur to Pune, 2 passengers" to a list using textContent, and show a running count of enquiries. Write the script so it would also work as a deferred file in the head.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Train Ticket Enquiry</title>
</head>
<body>
  <h1>Train ticket enquiry</h1>
  <form id="enquiry">
    <label for="from">From</label>
    <input id="from" name="from" required>
    <label for="to">To</label>
    <input id="to" name="to" required>
    <label for="people">Passengers</label>
    <input id="people" name="people" type="number" min="1" max="6" value="1" required>
    <button>Check</button>
  </form>
  <p>Enquiries: <output id="count">0</output></p>
  <ul id="results"></ul>
  <script>
    const form = document.querySelector("#enquiry");
    let count = 0;
    form.addEventListener("submit", (event) => {
      event.preventDefault();
      const data = new FormData(form);
      const li = document.createElement("li");
      li.textContent = data.get("from") + " to " + data.get("to") + ", " + data.get("people") + " passengers";
      document.querySelector("#results").append(li);
      count++;
      document.querySelector("#count").textContent = count;
      form.reset();
      form.from.focus();
    });
  </script>
</body>
</html>

The script only touches the page inside an event listener, so it would work unchanged in js/enquiry.js loaded with <script src="js/enquiry.js" defer> in the head. Station names go in with textContent, so typed HTML is shown as plain text.

Quick Quiz

1. A script in the head without defer calls document.querySelector("#total"). What does it get?

2. Which line safely shows a name typed by a user?

3. Which event should handle a form that should not reload the page?

4. Where can <noscript> content appear in the head?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call