Topic 7.8
HTML Interview Questions
In one line
The HTML questions interviewers ask most (semantic HTML, the doctype, data attributes, async and defer, accessibility and SEO) with model answers that show the mechanism, the trade-off and a real example.
Think of it like this
A driving test. The examiner doesn't only check that you know the rules ("stop at red"); they watch whether you understand why ("so cross traffic can go") and what you'd do in a tricky case ("the light is broken"). Good interview answers work the same way: what it is, how it works, why it matters, and an edge case.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Standards mode
- The browser's modern rendering mode, switched on by the doctype.
- Quirks mode
- A rendering mode that imitates old browser bugs, used when the doctype is missing.
- document.compatMode
- A JavaScript property that says the mode:
CSS1Compat(standards) orBackCompat(quirks). - dataset
- The JavaScript object holding an element's
data-*attributes, with camelCase names and string values. - defer
- A script attribute: download in parallel, run after the HTML is parsed, in order.
- async
- A script attribute: download in parallel, run as soon as it's ready, in any order.
- DOMContentLoaded
- The event fired when the HTML is fully parsed and deferred scripts have run.
- Core Web Vitals
- Google's page experience metrics: loading (LCP), responsiveness (INP) and visual stability (CLS).
Step by step
01Q: What is semantic HTML and why does it matter?
Model answer: Semantic HTML uses elements that describe their content's meaning, like header, nav, main, article, button and headings, instead of generic divs. The browser maps them to roles in the accessibility tree, so screen reader users can jump by landmarks and headings; interactive ones come with focus and keyboard behaviour; search engines and reader modes understand the structure; and the code is easier to read and test by role. Example: replacing clickable divs with <button> fixed keyboard access and removed custom key-handling code.
02Q: What does the doctype do?
Model answer: <!DOCTYPE html> must be the first thing in the document; it tells the browser to use standards mode. Without it the page uses quirks mode, which keeps legacy layout behaviours for very old pages, so CSS may behave differently (for example, table cell sizing and percentage heights). You can check with document.compatMode. It's not an HTML element and it's case-insensitive.
03Q: What are data attributes, and how do you read them?
Model answer: data-* attributes attach custom data to elements without inventing invalid attributes. In JavaScript, el.dataset.userId reads data-user-id (hyphens become camelCase); values are always strings, so convert numbers and booleans. CSS can select on them. Don't store sensitive data there (it's visible in the source) and don't use them for things HTML already has an attribute for.
<li data-product-id="42" data-price="199">Blue mug</li>
<script>
const li = document.querySelector("li");
const price = Number(li.dataset.price); // "199" -> 199
</script>04Q: Explain async versus defer.
Model answer: Both download the script without blocking the parser. defer waits until parsing is done and runs scripts in the order they appear, before DOMContentLoaded: right for app code that needs the DOM or depends on another script. async runs each script as soon as it arrives, in any order and possibly mid-parse: right for independent scripts like analytics. Module scripts are deferred by default. Both only apply to external scripts (src); async also works on inline module scripts.
05Q: How do you make a website accessible?
Model answer: Start with semantic HTML: landmarks, a logical heading outline, lists, real buttons and links. Give every image meaningful or empty alt, every field a visible label, groups a legend, and the page a lang. Make everything keyboard-operable with visible focus and a skip link. Meet AA contrast. Use ARIA only where HTML has no equivalent, and keep states in sync. Announce dynamic changes with live regions. Test with axe or Lighthouse, then manually with keyboard, zoom and a screen reader. Target WCAG 2.2 AA.
06Q: What HTML matters for SEO?
Model answer: A unique, descriptive <title> and meta description per page; one clear h1 and logical headings; real <a href> links with descriptive text so crawlers can follow them; alt text; a canonical link to avoid duplicates; lang and hreflang for languages; structured data in JSON-LD for rich results; server-rendered or static content so it's in the HTML; and fast, stable pages for Core Web Vitals. Good accessibility and good SEO overlap heavily.
07Q: What's the difference between <section>, <article> and <div>?
Model answer: <article> is a self-contained piece that would make sense on its own (a blog post, a product card, a comment). <section> is a thematic group within a document, normally with a heading; with an accessible name it becomes a region landmark. <div> has no meaning and is for styling or scripting hooks. If you can't give a section a heading, you probably want a div.
08Q: What happens if you put a block element inside a <p>?
Model answer: A p may only contain phrasing (inline-level) content. When the parser meets a div, ul, table or similar inside a p, it closes the paragraph automatically; the later </p> then creates an empty paragraph. The page may look nearly right, but the DOM differs from the source, so CSS selectors like .intro div and scripts break. The validator reports "No p element in scope but a p end tag seen".
Try it yourself
- 1
Predict dataset names
In the first example, add
data-max-qty="5"to the firstli. Predict how it appears in the loggedDOMStringMap, then run it. (maxQty: '5'.) - 2
Change the script order
In the second example, remove
deferfrom the data-URL script. Predict the new order before running. (It runs during parsing, before the inline script, so "3." prints first.) - 3
Answer out loud
Pick three walkthrough questions, cover the model answers and answer each aloud in under a minute using the four parts: define, mechanism, why, example. Then compare.
Code & diagrams
Every dataset value is a string: `"199"` must be converted before maths, and `"false"` is a truthy string, so compare with `=== "true"`.
Preview
Console
Nothing logged yet.Expected console output
this page: CSS1Compat
with doctype: CSS1Compat
without doctype: BackCompat
DOMStringMap { productId: '42', price: '199', inStock: 'true' }
string 200
in stock? true
trueThe deferred script appears first in the HTML but runs after parsing finishes, just before DOMContentLoaded. A `data:` URL stands in for a real file so the example works offline.
Preview
Console
Nothing logged yet.Expected console output
1. inline script in the body (during parsing)
2. script at the end of the body
3. deferred script (after parsing)
4. DOMContentLoaded
5. load (images and everything else done)Break it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Treat a dataset value as a boolean
Write if (li.dataset.inStock) { showBuyButton(); } for data-in-stock="false".
Break #2
Use async for scripts that depend on each other
Load <script async src="library.js"> and <script async src="app.js">, where app.js uses the library.
Myth vs fact
Myth
HTML5 is a separate version you opt into with special tags.
Fact
Today's HTML is the HTML Living Standard, maintained by WHATWG and updated continuously. "HTML5" is a historical name; <!DOCTYPE html> is all you need.
Myth
async is always faster than defer.
Fact
Both download in parallel. async may run earlier, but it can interrupt parsing and runs in random order. For app code, defer is usually the better choice.
Myth
Interviewers want you to recite definitions.
Fact
They want reasoning: the mechanism, a trade-off and a real example. A short, correct answer with one example beats a long list of facts.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
There are three modes, not two: no-quirks (standards), quirks, and limited-quirks ("almost standards"), triggered by some old transitional doctypes; limited-quirks differs only in how inline images in table cells are sized.
- ▸
Deferred and module scripts run before
DOMContentLoaded;asyncscripts may run before or after it. An inline<script>that comes after a stylesheet waits for that stylesheet to load (scripts may read styles), so a slow CSS file can also delay inline scripts. - ▸
datasetis aDOMStringMap; settingel.dataset.fooBar = 1writesdata-foo-bar="1", anddelete el.dataset.fooBarremoves the attribute. Names afterdata-must not contain uppercase ASCII letters in HTML (they're lowercased by the parser). - ▸
Interviewers for senior roles often follow up with "how would you enforce this on a team?": linting (html-validate, eslint-plugin-jsx-a11y), axe in CI, design-system components with built-in semantics, Lighthouse budgets, and accessibility in the definition of done.
Remember this
- 1
A strong answer has four parts. Define the thing in one sentence. Explain the mechanism: what the browser actually does. Give the trade-off or reason: why it matters for users, accessibility, performance or SEO. Show an example or edge case from real work. Keep it to about a minute; the interviewer will ask follow-ups if they want more.
- 2
Semantic HTML means choosing elements by meaning (
nav,main,article,button,h2) instead of genericdivs. The browser maps them to roles in the accessibility tree, gives built-in keyboard behaviour, and search engines and reader modes use the structure. Example: a<button>is focusable and firesclickon Enter and Space; a clickabledivdoes neither (Topic 7.7). - 3
The doctype
<!DOCTYPE html>switches the browser to standards mode; without it, the page renders in quirks mode, which emulates old browser bugs (for example, the old Internet Explorer box model in some cases, and table and percentage-height quirks). JavaScript can see the mode:document.compatModeis"CSS1Compat"in standards mode and"BackCompat"in quirks mode. HTML5's doctype is short because it no longer references a DTD (a formal grammar file used by older HTML and XHTML versions). - 4
**
data-*attributes** store custom data on elements for scripts and CSS:<li data-id="42" data-in-stock="true">. JavaScript reads them throughel.dataset, where names are converted to camelCase (data-in-stock→dataset.inStock); every value is a string. CSS can select them ([data-state="open"]) and show them (content: attr(data-label)). They're for private page data, not for accessibility or SEO (assistive tech and search engines ignore them). - 5
**
asyncanddefer**: a plain<script src>blocks HTML parsing while it downloads and runs.deferdownloads in parallel and runs after parsing finishes, in document order, beforeDOMContentLoaded.asyncdownloads in parallel and runs as soon as it arrives, in any order, possibly before parsing finishes. Modules (type="module") are deferred by default. Usedeferfor app scripts that need the DOM or depend on each other;asyncfor independent scripts like analytics (Topic 6.5). - 6
Accessibility and SEO questions usually test the same foundations: semantic structure, one clear
h1and logical headings, alt text, labels, link text,lang, keyboard support, and when (not) to use ARIA. For SEO add: a unique<title>and meta description per page, canonical URLs, crawlable links (<a href>, not click handlers), structured data (JSON-LD), and fast, stable pages (Core Web Vitals). Phase 6 and Topics 7.1–7.5 have the details.
Explain it without notes
Explain the difference between <script>, <script defer>, <script async> and <script type="module">.
What is the difference between an element's attributes and its dataset? When would you use data-*?
Why should you use <button> instead of <div onclick>? Give at least four reasons.
What is the accessibility tree, and how do HTML choices affect it?
A page ranks poorly and screen reader users complain. Which HTML would you check first?
Practice
Write a product list item that stores a product id and price for JavaScript, then write the JavaScript that reads the price as a number and adds 18% tax.
Write the <head> script tags for: an analytics script that doesn't depend on anything, a library, and your app code that uses the library. Explain your choice.
Write a 4-part answer (define, mechanism, why, example) to: "Why does every page need a lang attribute?"
Trade-offs
- ↔
Long, complete interview answers show depth but can lose the interviewer; lead with a one-sentence answer, then offer the mechanism and an example, and let them steer.
- ↔
asynccan start scripts earliest, but its unpredictable order costs debugging time;deferis predictable and nearly as fast for most apps.
Done when you can
I can answer "what is semantic HTML" with mechanism and example.
I can explain the doctype, quirks mode and
document.compatMode.I can read and write
data-*attributes throughdataset, remembering values are strings.I can explain and choose between plain,
defer,asyncand module scripts.I can give a structured answer on accessibility and on HTML for SEO.