Workbench / Volume 2 Exercises: The Web Frontend
V2·13
HTML
Exercises for Volume 2, chapter 13: elements, tags and attributes, the document skeleton and metadata (charset, viewport, language), text semantics, headings, sections and landmarks, links versus buttons, images (alt text, dimensions, srcset and sizes, lazy loading), tables, media, iframes, SVG and canvas, implicit semantics, content models and the parser's error recovery, default browser behaviour, accessibility, forms (submission, input types, labels, fieldsets, select and textarea, validation, autocomplete, FormData, multipart and files), and loading scripts and modules. 12 theory questions, 12 programming exercises, 3 cumulative projects with Volume 1 and Volume 2 so far, the concepts the chapter leaves out, and 6 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. HTML looks simple, so the exercises focus on what it does: what the parser builds from imperfect markup, what the browser gives you for free (keyboard support, validation, form submission, image selection), and what reaches assistive technology and the server. You'll need a browser with DevTools and a small local server (python3 -m http.server, or any backend that logs requests) so you can see what forms send.
Outputs come from Chromium 153 (via Playwright) in this book's sandbox. Two results surprised even me, and they're kept in because they're real: a page served without a character encoding garbled ₹ in two different ways at once (P3), and Chromium's fast innerHTML path nested two buttons that the full parser keeps apart (P1's note).
Coverage map.
| Chapter component | Exercises |
|---|---|
| elements, tags, attributes; the parser and error recovery; content models | T1, P1 |
| the skeleton and metadata: doctype, charset, viewport, lang, title | T2, P3 |
| text semantics, headings, sections and landmarks | T3, P4 |
| links and buttons; default browser behaviour | T4, P2, P5 |
| images: alt, width/height, srcset/sizes, lazy loading, picture | T5, P6 |
| tables | T6, P7 |
| media, embeds, iframes, SVG, canvas | T7 |
| implicit semantics and accessibility implications | T3, T8, P4 |
| forms: anatomy, submission, encoding, GET vs POST | T9, P2, P8 |
| input types, labels, fieldsets, select, textarea, autocomplete | T10, P9 |
| validation (constraint validation API) | T11, P10 |
| FormData, multipart, file inputs | T9, P11 |
| dialog and details (interactive elements) | T8, P12 |
| loading scripts and resources; modules and modulepreload | T12 |
Theory
T1. Elements, the parser and content models
- Distinguish tags, elements, attributes and the DOM nodes they become. What's a void element, and which boolean attributes do you use often?
- P1 fed imperfect markup to the HTML parser. Explain each repair:
<p>one<p>twobecame two paragraphs;<p>intro<div>block</div>after</p>became<p>intro</p><div>block</div>after<p></p>;<b><i>bold italic</b> only italic?</i>became<b><i>bold italic</i></b><i> only italic?</i>; a<div>inside a<table>was moved before the table; a link inside a link was split into two links. - Why does the HTML parser never "fail" like an XML parser, and what are the consequences for frameworks and for security (mutation XSS)?
T2. The skeleton and metadata
- Write the minimal correct skeleton for a TiffinBox page in English with a Hindi phrase inside it, and justify each line: doctype,
lang,<meta charset>, the viewport meta,<title>, a description, and a canonical link. - P3 served UTF-8 bytes with
Content-Type: text/html(no charset) and no<meta charset>: Chromium decoded it as windows-1252 and₹149 — naïve cafédisplayed as₹149 — naïve café. Explain byte by byte (Volume 1, chapter 06), and say where the charset should be declared. - What happens without the viewport meta on a phone, and why should you never disable zoom (
user-scalable=no)?
T3. Text semantics, headings and landmarks
- Rewrite this "div soup" with the right elements, and say what each change gives users and machines:
<div class="header"><div class="logo">TiffinBox</div><div class="nav"><span onclick="go('/menu')">Menu</span></div></div><div class="main"><div class="title">Amma's Kitchen</div><div class="dish"><div class="name">Dal</div><div class="price">₹149</div></div></div><div class="footer">© 2026</div>. - P4 listed the headings of a page as H1, H3, H2. Why is skipping levels a problem, how do screen-reader users use headings and landmarks, and how many
<h1>s should a page have? - When should you use
<strong>vs<b>,<em>vs<i>,<time>,<data>,<abbr>,<address>,<mark>and<small>?
T4. Links versus buttons, and default behaviour
- State the rule for choosing
<a href>versus<button>, and list what each gives you for free (keyboard, focus, context menu, middle-click, announced role, form behaviour). - P2 found that a
<button>with notypeinside a form submitted the form when clicked ("Cancel" navigated to/x), whiletype="button"didn't. Explain the default and the bug pattern it causes. - P5 opened a
target="_blank"link and the new tab'swindow.openerwasnull. Why, and when do you still addrel="noopener noreferrer"explicitly? - Name three other "free" behaviours of native elements that custom components must re-implement (and usually don't).
T5. Images
- When should
altdescribe the image, be empty, or be absent? Writealttext for: the kitchen's logo linking to its page, a decorative divider, a photo of paneer tikka on a menu, a chart of weekly orders, and an icon-only "Add to cart" button. - Why must images have
widthandheightattributes even in responsive layouts? (The chapter's lab measured CLS 0.301 without them and 0 with.) - P6 gave an image
srcset="…-480w, …-960w, …-1920w"andsizes="(max-width: 600px) 100vw, 50vw". Explain why the browser chose 480 at 375 px DPR 1, 960 at 375 px DPR 2, 1920 at DPR 3, 960 at 1280 px DPR 1 and 1920 at 1280 px DPR 2. - When do you use
loading="lazy",fetchpriority="high",decoding="async"and<picture>with<source type="image/avif">?
T6. Tables
- When is a table the right element, and when is it wrong (layout, card lists)? Mark up a kitchen's weekly delivery schedule (days as columns, meal slots as rows) with
caption,thead,th scopeandtbody. - What do screen readers do with a table that has proper
thelements, and what happens when a table is built fromdivs with CSS grid? - How do you make a wide data table usable on a phone without breaking its semantics?
T7. Media, iframes, SVG and canvas
- What do
<video>and<audio>need for accessibility and performance (captions with<track>,controls,preload,poster, autoplay rules)? - When embedding a third-party map or video with
<iframe>, which attributes do you add for security, privacy and performance (sandbox,allow,loading,title,referrerpolicy)? - Compare inline SVG,
<img src="x.svg">, and<canvas>for an icon set, a kitchen-location map marker, an orders chart, and a drawing game. What does each mean for accessibility, styling and events?
T8. Implicit semantics, ARIA and interactive elements
- What is an element's implicit ARIA role? Give the roles of
<button>,<a href>,<a>withouthref,<nav>,<main>,<ul>,<input type="checkbox">,<input type="search">,<section>(with and without an accessible name) and<dialog>. - State the "first rule of ARIA" and give three examples of ARIA that makes things worse (
role="button"on a div without keyboard support,aria-hidden="true"on a focusable element, overriding native semantics like<h2 role="button">). - P12 opened a
<dialog>withshowModal(): focus moved into it, the page behind became inert, and Escape closed it. Compare with a custom modal made ofdivs; what must the custom one implement? Also, what do<details>/<summary>give you?
T9. How forms submit
- P2 submitted a form with: a text field, a field containing
extra ₹20 & no onion, an unchecked and a checked checkbox, adisabledfield, areadonlyfield, and a<select multiple>with two selected options. The server receivedname=Asha+K¬e=extra+%E2%82%B920+%26+no+onion&cutlery=on&kitchen=42&dishes=dal&dishes=roti. Explain every part, including what's missing. - Compare GET and POST forms (P2's search form went to
/search?q=masala+dosa+%E2%82%B9),application/x-www-form-urlencodedandmultipart/form-data. When do you use each? - What's the Post/Redirect/Get pattern, and what bug does it prevent?
- Why must the server validate everything again, even with perfect client-side validation?
T10. Input types, labels and autocomplete
- For a delivery address form (name, phone, email, flat/house, street, area, city, PIN code, delivery date and time slot, number of guests, instructions), choose each field's element,
type,inputmode,autocompletevalue and any attributes (maxlength,pattern), and explain whytype="number"is wrong for the PIN code and phone. - Why must every input have a programmatic label, what are the three ways to provide one, and why is
placeholdernot a label? - When do you use
<fieldset>and<legend>? Show them for "Meal preference: veg / non-veg / Jain" as radio buttons.
T11. Validation
- P10's form had a phone
12345againstpattern="[6-9][0-9]{9}", guests2.5withstep="1", a date beforemin, an uncheckedrequiredcheckbox, and a coupon marked invalid withsetCustomValidity('This coupon has expired.'). List theValidityStateflag and message for each (P10 printed them), and what the browser did when the user clicked Order. - What are the limits of built-in validation messages (language, timing, styling, screen readers), and how do you build a better experience while keeping the constraint validation API?
- Why should
patternandmaxlengthon the client match the server's rules, and how do you keep them in sync?
T12. Loading scripts and modules from HTML
- Summarise when to use classic
<script>,defer,asyncandtype="module"(chapter 12's T7), and whatnomodulewas for. - The chapter's lab measured a module graph a → b → c (200 ms per file) finishing at 644 ms without
modulepreloadand 218 ms with it. Explain the waterfall and how<link rel="modulepreload">(or bundling) fixes it. - What do import maps do, and why might TiffinBox use them instead of a bundler for a small internal admin page?
Programming exercises
P1. What the parser builds
In the browser console, use new DOMParser().parseFromString('<!doctype html><body>' + markup, 'text/html').body.innerHTML to see the DOM built from: <p>one<p>two, <ul><li>a<li>b</ul>, <p>intro<div>block</div>after</p>, <b><i>bold italic</b> only italic?</i>, <table><tr><td>1</td></tr><div>stray</div></table>, a link inside a link, and a button inside a button. Predict each result first. Then validate a page of yours with the W3C validator (validator.w3.org/nu) and fix what it reports.
P2. What a form really sends
Serve a page with a POST form containing: a text field name, a field note with the value extra ₹20 & no onion, two checkboxes (one checked), a disabled field, a readonly field, a <select multiple> with two options selected, a type="button" Cancel and a submit button. Log the request body on the server. Then click the Cancel button, and a second form's <button> with no type. Finally, submit a GET search form with masala dosa ₹ and look at the URL. Remember to declare the page's charset (or see P3 first).
P3. The missing charset
Serve a page whose bytes are UTF-8 (₹149 — naïve café) with Content-Type: text/html and no charset parameter, and without <meta charset>. Read document.characterSet and the text. Then add a form to such a page with a field containing extra ₹20 & no onion, and compare (a) what the form submits natively and (b) what new URLSearchParams(new FormData(form)) produces. Fix the page and repeat.
P4. Headings, landmarks and the outline
Take a real page you've built (or the T3 rewrite), list its headings in order with [...document.querySelectorAll('h1,h2,h3,h4,h5,h6')].map(h => h.tagName + ' ' + h.textContent), and its landmarks with DevTools' Accessibility tree or Playwright's aria_snapshot(). Fix skipped levels and missing landmarks. Then navigate it with a screen reader (NVDA on Windows, VoiceOver on macOS/iOS, TalkBack on Android) using only heading and landmark shortcuts, and write down what was confusing.
P5. Links, buttons and target=_blank
Build a page with: an <a href> to /menu, a <button type="button"> that adds to a cart, a <div onclick> that does the same, an <a href="#" onclick> that does the same, and a target="_blank" link. Test each with the keyboard only (Tab, Enter, Space), with middle-click, and with a screen reader's links and buttons lists. In the new tab, check window.opener.
P6. Responsive images, measured
Create an image with srcset candidates at 480w, 960w and 1920w and sizes="(max-width: 600px) 100vw, 50vw". Open it with DevTools' device emulation at 375 px wide with DPR 1, 2 and 3, and at 1280 px with DPR 1 and 2 (or with Playwright contexts), and read img.currentSrc each time. Then remove sizes and repeat at 1280 px DPR 1. Finally, check the LCP image of a page you know: does it have width/height, fetchpriority="high", no loading="lazy"?
P7. An accessible data table
Mark up TiffinBox's "Your orders" history as a table (order number, date, kitchen, items, total, status) with a caption, header cells with scope, the total right-aligned with <data value> in paise, dates in <time datetime>, and a scrollable wrapper for phones. Check it with a screen reader's table navigation and DevTools' accessibility tree. Then build the same with divs and CSS grid and compare what's announced.
P8. Post/Redirect/Get and double submission
Write a small server (Java or Python) with an order form: POST /orders creates an order and (a) returns an HTML "Thank you" page directly, or (b) responds 303 See Other with Location: /orders/{id}. In each version, place an order, then press reload and Back/Forward, and double-click the submit button quickly. Count orders created. Then add an idempotency key (a hidden field generated per form render) and a disabled-on-submit button, and repeat.
P9. A labelled, autofill-friendly address form
Build T10's delivery address form with correct elements, types, inputmode, autocomplete tokens, labels and a fieldset for the meal preference radios. Test on a phone (or device emulation): which keyboard appears for each field? Test autofill with a saved address in Chrome. Test clicking each label. Then test with a screen reader that every field is announced with its label, type and state.
P10. The constraint validation API
Build a form with: a phone with required and pattern="[6-9][0-9]{9}", a guests field type="number" min="1" max="10" step="1", a date with min set to today, a required terms checkbox, and a coupon field validated with setCustomValidity. Fill in invalid values and print each field's validity flags and validationMessage; click submit and note what happens. Then add novalidate and implement inline messages with aria-describedby and aria-invalid, moving focus to the first invalid field on submit.
P11. Files, multipart and FormData from JavaScript
Build a "Upload a photo of your dish" form with <input type="file" accept="image/*" capture="environment">, enctype="multipart/form-data", and a text field. Log the raw request on the server to see the boundary and parts. Then submit the same with fetch(url, {method: 'POST', body: new FormData(form)}) and show a preview of the image before upload with URL.createObjectURL. On the server, enforce a size limit and check the file's real type (magic bytes), not just its name or Content-Type.
P12. dialog and details
Build a "Confirm order" modal with <dialog> and showModal(), with OK and Cancel buttons and a form inside with method="dialog". Check: where focus goes on open, whether Tab escapes the dialog, whether the page behind can be clicked, what Escape does, where focus returns on close, and the returnValue. Build an FAQ with <details>/<summary> and check the keyboard and screen-reader behaviour. Then try the same modal built from divs and list everything you had to add.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12 and 13)
C1. A complete, accessible checkout without JavaScript
Build TiffinBox's checkout as server-rendered HTML with a Java backend (any framework, or Volume 1, chapter 09's C1 server): cart review (a table), delivery address (P9's form), time slot (<select>), meal preference (fieldset with radios), payment method choice, and order placement with PRG and an idempotency key. It must work completely without JavaScript, pass the W3C validator, have correct headings and landmarks, server-side validation errors shown next to fields (with the user's input preserved), UTF-8 everywhere, and correct prices recomputed on the server. Then add progressive enhancement: client-side validation messages (P10) and an "Add another address" toggle with <details>.
Combines: HTTP, forms over the wire and status codes (Vol 1 ch 09); server-side validation and error handling (ch 02); money in paise and UTF-8 (ch 06); idempotency (ch 09, 11); this volume's origins and cookies (ch 12) and all of this chapter.
C2. A menu page that's fast on a ₹8,000 phone
Build the kitchen menu page (50 dishes with photos, prices, veg markers, a filter form) as HTML and CSS with minimal JavaScript, and measure it with Lighthouse and WebPageTest (or Chrome DevTools with "Low-tier mobile" CPU throttling and "Slow 4G"). Targets: LCP under 2.5 s, CLS under 0.1, total JavaScript under 30 KB. Use responsive images with correct sizes, dimensions on every image, lazy loading below the fold, fetchpriority on the first image, semantic markup, and a GET filter form. Report each measurement before and after each change.
Combines: compression and byte sizes (Vol 1 ch 06); latency and bandwidth (ch 07, 09); caching headers and connection reuse (ch 09); this volume's loading rules (ch 12) and images, forms and semantics (ch 13).
C3. Internationalised, accessible forms
Make P9's address form work in English, Hindi and Telugu: lang on <html> and on inline phrases, translated labels and error messages, numerals (Western Arabic digits in inputs, with Devanagari or Telugu digits accepted and normalised server-side), name fields that don't assume first/last names, PIN codes and phone numbers validated without rejecting valid input, and a date picker that displays dates in the user's locale. Test with a screen reader in each language and with input typed in each script.
Combines: Unicode, UTF-8, normalisation and digits (Vol 1 ch 06 and Volume 23); server validation (ch 02); parsing (ch 10); this volume's URL encoding and storage (ch 12) and forms and validation (ch 13).
What the chapter leaves out
Structured data and link previews
Search engines and social apps read machine-readable data from HTML: JSON-LD (<script type="application/ld+json"> with schema.org types like Restaurant, Menu, Offer, AggregateRating) enables rich results (prices, ratings, opening hours in search); Open Graph and Twitter card meta tags (og:title, og:image, og:description) control previews in WhatsApp, Slack and social networks, which for a food app may matter more than search. Test with Google's Rich Results Test and by pasting links into the apps themselves; keep the data consistent with the visible page (search engines penalise mismatches).
HTML security beyond scripts
XSS isn't only <script>: dangerous sinks include href="javascript:…" (validate URL schemes on user-supplied links), srcdoc and src on iframes, event-handler attributes (onerror, onload), <form action> pointing elsewhere (CSP's form-action), <base href> hijacking relative URLs (CSP's base-uri), and dangling markup injection (an unclosed attribute that captures the rest of the page into a URL). DOM clobbering: elements with id or name become properties of window and document (<img name="config"> overrides document.config), so code reading globals can be subverted by injected HTML even without scripts. Sanitise with DOMPurify (or the Sanitizer API), escape attribute values contextually, and keep the CSP strict.
Web components and custom elements
HTML can be extended with custom elements (customElements.define('tb-dish-card', class extends HTMLElement {…})), shadow DOM (encapsulated markup and styles), <template> and <slot>. They let a design system ship framework-independent components usable in React, Angular or plain HTML pages. Trade-offs: accessibility across shadow boundaries needs care (labels can't reference IDs inside another shadow root without newer features like reference target), server rendering needs declarative shadow DOM (<template shadowrootmode="open">), and forms need ElementInternals (formAssociated) to participate in submission and validation. Chapter 21 discusses where they fit.
Email HTML
Transactional emails (order confirmations) are HTML too, but rendered by email clients with ancient, inconsistent engines (Outlook on Windows uses Word's renderer): table-based layout, inline styles, no scripts, limited CSS, images blocked by default (so alt text and text content matter), dark-mode inversions, and 102 KB clipping in Gmail. Use a framework built for it (MJML) and test with tools that render across clients. Include a plain-text alternative part; many readers and spam filters use it.
Printing and other media
Pages get printed (receipts, invoices, recipes) and saved as PDF: @media print styles hide navigation, show link URLs (a::after { content: " (" attr(href) ")" }), avoid breaking table rows across pages (break-inside: avoid), and use print-friendly colours. For invoices that must look exactly right, generate the PDF server-side from HTML with a headless browser (the same engine your users have) rather than relying on users' print dialogs.
Validation tooling in the development loop
Catch HTML problems before users do: the Nu HTML Checker (W3C validator) in CI for server-rendered templates, axe-core (via Playwright, Cypress or jest-axe) for automated accessibility checks (it finds roughly a third to a half of issues: missing labels, contrast, invalid ARIA, duplicate IDs), eslint-plugin-jsx-a11y or Angular's template lint rules for framework code, and Lighthouse in CI with budgets. Automated checks find the mechanical problems; keyboard and screen-reader testing (P4) find the rest.
Senior exercises
S1. Review a pull request's markup
A PR adds a "Rate your meal" feature: a <div class="stars"> of five <span>s with onclick handlers, a <textarea> with only placeholder="Tell us more", a "Skip" <button> and a "Submit" <button> inside a <form>, a success message inserted with innerHTML = '<p>Thanks ' + userName + '!</p>', and a photo upload with <input type="file"> posting via fetch with headers: {'Content-Type': 'multipart/form-data'}. Write the review, ranked by severity.
S2. Set HTML standards for a frontend team
Write a one-page HTML standards document for TiffinBox's frontend teams: the rules (with one-line reasons), how each is enforced automatically, and how exceptions are approved. Cover document metadata, semantics, links and buttons, images, forms, tables, ARIA, and security-relevant markup.
S3. Decide between native form controls and a component library
A designer wants fully custom-styled date pickers, selects, checkboxes and radios that look identical on all platforms. A component library offers them as div-based widgets. Analyse the trade-offs for TiffinBox's mobile-heavy audience, and recommend an approach per control, including what to test if you go custom.
S4. Fix a production bug: garbled names in order confirmations
Customers with names in Hindi and Telugu report that their confirmation emails and order pages show अमित instead of अमित, but only for orders placed through the new checkout page; old orders are fine. Using P3 and Volume 1, chapter 06, diagnose the likely cause, describe how you'd confirm it in 30 minutes, the fix, how to repair the stored data, and how to prevent it.
S5. Plan an accessibility audit and remediation
TiffinBox has received a complaint that its ordering flow is unusable with a screen reader, and legal points out accessibility obligations (India's Rights of Persons with Disabilities Act, and WCAG 2.1/2.2 AA as the usual technical standard; the European Accessibility Act for EU customers). Plan the audit (scope, methods, tools, people), how you'd prioritise findings, the remediation plan, and how to stop regressions.
S6. Explain "use the platform" to a framework-first team
Your team builds everything as framework components and rarely writes plain HTML elements directly. Prepare a 15-minute talk with three demos from this chapter showing what native HTML gives for free, the costs of re-implementing it, and a practical proposal that fits their framework (not "stop using the framework").