Skip to the content.

HTML5 Scenario-Based MCQ

Scenario-based multiple choice questions covering core HTML5 topics.


Table of Contents

  1. Semantic Elements
  2. Forms & Validation Attributes
  3. HTML5 Input Types
  4. Media — Audio, Video & Canvas
  5. Browser Storage
  6. Accessibility
  7. Semantics (Advanced)
  8. Responsive Images
  9. Web APIs
  10. Custom Data Attributes
  11. Meta & Document Head
  12. SVG
  13. WebSocket API
  14. IFrame & Sandbox
  15. Progress, Meter, Time & Dialog


1. Semantic Elements

Q1. You are building a news website. The page has a site-wide navigation bar at the top, a main article in the centre, a sidebar with related links, and a copyright notice at the bottom. Which combination of semantic elements best structures this page?

Answer: B
<nav>, <main>, <aside>, and <footer> are the correct HTML5 semantic elements for site navigation, primary content, supplementary content, and page footer respectively.

↥ back to top

Q2. A developer renders a blog post that contains a heading, body text, and a publication date. Which element should wrap the entire blog post so that search engines and screen readers correctly identify it as a self-contained piece of content?

Answer: C
<article> represents a self-contained, independently distributable piece of content such as a blog post, news story, or forum entry.

↥ back to top

Q3. While reviewing a teammate's code you notice:

<section>
  <p>Copyright © 2026 Acme Corp. All rights reserved.</p>
</section>

What is the most semantically correct replacement for <section> here?

Answer: B
<footer> is the appropriate semantic element for copyright information, contact details, and other footer content associated with its nearest sectioning ancestor.

↥ back to top

Q4. A documentation site groups related topics under expandable headings. Each group has a visible title and hidden details that toggle on click. Without any JavaScript, which HTML5 element pair enables this behaviour natively?

Answer: B
The <details> / <summary> element pair provides a native browser-controlled disclosure widget — no JavaScript required.

↥ back to top

Q5. A recipe website uses the same header (logo + nav) on every page and the same footer (links + copyright). A developer wraps each in <header> and <footer> tags respectively. A junior colleague says this is wrong because only one <header> and one <footer> is allowed per page. Who is correct?

Answer: B
<header> and <footer> are not limited to one per page. They can appear inside any sectioning element (<article>, <section>, <aside>, <nav>).

↥ back to top

2. Forms & Validation Attributes

Q6. A registration form has an email field that must be filled in before submission. The field should also show a custom error message “Please enter a valid company email” when invalid. Which markup achieves both requirements using only HTML5 attributes?

Answer: B
required enforces a non-empty value and title provides the tooltip/hint text that browsers display as the validation message. (For fully custom messages setCustomValidity() is used in JS, but title is the HTML-only approach.)

↥ back to top

Q7. A password field must be between 8 and 20 characters and contain only alphanumeric characters. Which HTML5 attributes enforce these constraints without JavaScript?

Answer: C
minlength and maxlength control character count, while pattern applies a regex constraint. min/max apply to numeric/date inputs, not text.

↥ back to top

Q8. A checkout form has multiple sections: personal info, shipping address, and payment. The designer wants the browser's autofill to correctly distinguish between the “billing email” and the “shipping email” fields. Which attribute enables this?

Answer: C
The autocomplete attribute with values like billing email and shipping email tells the browser exactly what data each field expects, enabling accurate autofill.

↥ back to top

Q9. A developer writes the following form:

<form>
  <input type="text" name="city">
  <button type="button">Submit</button>
</form>

A tester reports the form never validates even though required was added to the input. What is the cause?

Answer: B
type="button" does not submit the form and therefore never triggers HTML5 constraint validation. It must be type="submit" (or omit type, which defaults to submit).

↥ back to top

Q10. A survey form has a “Rating” field that accepts only whole numbers from 1 to 10, in steps of 1. Which input correctly enforces this?

Answer: D
Both type="number" (text-entry with spinner) and type="range" (slider) accept min, max, and step. The right choice depends on UX preference, but both enforce the constraint.

↥ back to top

3. HTML5 Input Types

Q11. A travel booking site needs a field where users enter their departure date. The field should display a native date-picker on supported browsers and store the value in YYYY-MM-DD format. Which input type should be used?

Answer: C
type="date" renders a native date-picker and stores the value in YYYY-MM-DD format. type="datetime" is not a valid HTML5 input type (datetime-local is).

↥ back to top

Q12. An e-commerce site lets users pick a product colour. The developer wants the browser's native colour-picker widget with no extra libraries. Which input type should be used?

Answer: B
type="color" invokes the OS/browser native colour-picker and returns a hex colour string.

↥ back to top

Q13. A fitness app collects data via a mobile form. For the “Weight (kg)” field, the developer wants the numeric keypad to open automatically on mobile devices and prevent non-numeric input. Which input type is most appropriate?

Answer: C
type="number" opens the numeric keyboard on mobile and restricts input to valid numbers. While inputmode="numeric" on a type="text" opens a numeric keyboard, it does not restrict non-numeric input at the browser level.

↥ back to top

Q14. A website's search bar should suggest previously entered searches from the browser history AND from a server-provided list of popular queries as the user types. Which HTML5 feature supports the server-provided suggestions natively?

Answer: B
The list attribute paired with a <datalist> element provides a dropdown of predefined options that the browser merges with its autocomplete history.

↥ back to top

Q15. A developer uses <input type="hidden"> to pass a CSRF token through a form. A colleague suggests this is a security risk because the value is visible in the page source. What is the correct assessment?

Answer: C
CSRF tokens are not secret from the current page — they must be readable by the legitimate form. The protection relies on the server validating that the token in the request matches the user's session, which cross-origin requests cannot access.

↥ back to top

4. Media — Audio, Video & Canvas

Q16. A developer is embedding a promotional video that should play automatically and silently when the page loads, loop continuously, and never show playback controls. Which attribute combination achieves this?

Answer: A
autoplay, loop, and muted are valid HTML5 <video> attributes. Most browsers require muted for autoplay to work without user interaction. There is no controls="false" — omitting controls hides them.

↥ back to top

Q17. A video element must support three formats to maximise browser compatibility. The browser should pick the first format it supports. How should this be marked up?

- B)
```html
<video>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.webm" type="video/webm">
  <source src="movie.ogv" type="video/ogg">
</video>
- D)
```html
<video src="movie.mp4" fallback="movie.webm,movie.ogv"></video>

Answer: B
Multiple <source> child elements inside <video> allow the browser to try each in order and use the first one it can decode.

↥ back to top

Q18. A data dashboard needs to draw a bar chart that updates every second with live data. The chart involves pixel-level custom rendering. Which HTML5 element is the best fit?

Answer: B
<canvas> provides a pixel-based 2D (and WebGL) drawing API suited for dynamic, frequently updated graphics. SVG is better for static or interactively-selected vector graphics.

↥ back to top

Q19. A developer writes the following Canvas code but the text never appears:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '20px Arial';
ctx.fillText('Hello World', 10, 50);

A colleague points out the canvas element in HTML has no width or height attributes. What is the likely issue?

Answer: B
Without explicit width/height attributes the canvas defaults to 300×150 px. Sizing only with CSS stretches the canvas, distorting the coordinate system. Always set width and height as HTML attributes to define the drawing buffer size.

↥ back to top

Q20. An accessibility auditor flags that an <audio> element on a podcast page has no text alternative. What is the recommended HTML5-compliant fix?

Answer: B
<audio> does not support alt. Accessibility best practice is to provide controls (so keyboard users can operate it) and a text transcript. <track> elements can also be used for descriptions.

↥ back to top

5. Browser Storage

Q21. A single-page application stores the user's theme preference (dark/light). The preference should persist across browser restarts but only for that origin. Which storage mechanism is most appropriate?

Answer: B
localStorage persists data with no expiry across sessions for the same origin. sessionStorage is cleared when the tab is closed, cookies expire and travel with every HTTP request, and IndexedDB is overkill for a single string value.

↥ back to top

Q22. A collaborative document editor needs to store megabytes of structured JSON data (revision history) client-side and query it efficiently. Which browser storage option is the best fit?

Answer: C
IndexedDB is a transactional, indexed, NoSQL database in the browser designed for large amounts of structured data. localStorage is limited to ~5 MB of strings and has no query capability.

↥ back to top

Q23. A developer stores a JWT in localStorage to keep a user logged in. A security consultant flags this. What is the primary concern?

Answer: B
Any JavaScript running on the page — including injected malicious scripts — can read localStorage. An HttpOnly cookie prevents this because it is inaccessible to JavaScript.

↥ back to top

Q24. A user fills out a long multi-step form. The developer uses sessionStorage to save progress between steps. The user accidentally closes the tab and reopens the page. What happens to the saved form data?

Answer: B
sessionStorage is scoped to the tab (browsing context). Closing the tab destroys the session and all its sessionStorage data.

↥ back to top

Q25. Examine the following code:

localStorage.setItem('cart', { items: ['book', 'pen'], total: 150 });
console.log(localStorage.getItem('cart'));

What does the console output?

Answer: B
localStorage stores only strings. When an object is passed to setItem without JSON.stringify(), the object's .toString() is called, producing "[object Object]". Use JSON.stringify() before storing and JSON.parse() after retrieving.

↥ back to top

6. Accessibility

Q26. A designer creates a decorative divider image (a horizontal flourish). A screen reader user is reading the page. What is the correct way to mark up this image so screen readers skip it?

Answer: B
An empty alt="" tells screen readers the image is decorative and should be skipped. Omitting alt entirely causes some screen readers to announce the file name. role="none" suppresses the role but does not replace the need for an empty alt.

↥ back to top

Q27. A modal dialog opens when a user clicks a “Help” button. A keyboard-only user reports they cannot interact with the modal content because the Tab key moves focus to elements behind the modal. What ARIA or HTML technique addresses this?

Answer: B
A focus trap ensures keyboard focus cannot leave the modal. aria-modal="true" signals to assistive technologies that content behind the dialog is inert. role="dialog" alone does not trap focus.

↥ back to top

Q28. A form has a custom-styled checkbox built from a <div>. A screen reader user cannot determine the checkbox state or interact with it. What is the minimum change to make it accessible without replacing the <div>?

Answer: B
role="checkbox" declares the element's purpose, aria-checked communicates its state, and tabindex="0" makes it keyboard-focusable. All three are required for basic accessibility.

↥ back to top

Q29. A developer adds the following to a navigation landmark:

<nav aria-label="Main navigation">...</nav>
<nav aria-label="Footer navigation">...</nav>

A colleague says using aria-label on <nav> is redundant. Who is correct?

Answer: B
When a page has more than one landmark of the same type, WCAG recommends labelling each with aria-label or aria-labelledby so users can distinguish between them in the landmark list.

↥ back to top

Q30. An icon-only button uses a magnifying glass SVG for “Search”. A blind user navigates to the button and hears nothing descriptive. Which is the correct accessible fix?

Answer: B
aria-label="Search" on the <button> provides the accessible name. aria-hidden="true" on the SVG prevents the screen reader from announcing SVG internals (paths, groups) as duplicate content.

↥ back to top

7. Semantics (Advanced)

Q31. A developer adds the following markup to a product listing:

<div itemscope itemtype="https://schema.org/Product">
  <span itemprop="name">Wireless Headphones</span>
  <span itemprop="price">$49.99</span>
</div>

What HTML5 feature is being used and what is its purpose?

Answer: B
itemscope, itemtype, and itemprop are HTML5 Microdata attributes. They annotate content with structured data vocabularies (such as Schema.org) that search engines use to generate rich results.

↥ back to top

Q32. A developer must mark up an abbreviation on first use so that its full form is available to all users including those using screen readers. Which markup is correct?

Answer: B
<abbr> is the correct semantic element for abbreviations and acronyms. The title attribute provides the expansion, which browsers display as a tooltip and some screen readers announce. <acronym> was removed in HTML5.

↥ back to top

Q33. A legal document page contains a passage that was recently changed. The old price “$40” was replaced with “$35”. Which HTML5 markup correctly represents this edit so that the change is semantically conveyed?

Answer: B
<del> marks content that has been removed and <ins> marks content that has been inserted. Both carry semantic meaning that assistive technologies and search engines can interpret. <s> indicates content that is no longer accurate but does not imply an edit.

↥ back to top

Q34. A blog engine outputs breadcrumbs as an ordered list: Home > Blog > Article. Which semantic element should wrap the breadcrumb trail?

Answer: B
Breadcrumbs are a navigational structure, so <nav> is the correct wrapper. An <ol> conveys the ordered hierarchy. aria-label="Breadcrumb" distinguishes this <nav> from others on the page.

↥ back to top

Q35. A developer builds a side panel that shows supplementary content — author bio, related articles — next to the main article on a blog. Which element should wrap this side panel?

Answer: C
<aside> represents content tangentially related to the surrounding content — perfect for author bios, ads, and related links placed beside the main content. <sidebar> is not a valid HTML5 element.

↥ back to top

Q36. The following page outline is produced by a screen reader's heading navigation:

H1: Company Name
H3: Our Products
H2: Contact Us

What is wrong with this structure?

Answer: B
Heading levels should not skip ranks (e.g., H1 → H3) because screen reader users navigate by heading level to understand document structure. Skipping levels breaks the expected outline.

↥ back to top

Q37. A developer needs to display a table of data showing quarterly sales figures. Each column has a header. Which attribute ensures screen readers correctly associate data cells with column headers?

Answer: B
scope="col" on a <th> element explicitly declares that the header applies to all cells in its column. This is the standard HTML attribute for associating column headers with data cells.

↥ back to top

Q38. An online magazine uses the following structure:

<body>
  <header>...</header>
  <main>
    <article>
      <header><h1>Article Title</h1></header>
      <p>Content...</p>
      <footer><p>Published by Jane</p></footer>
    </article>
  </main>
  <footer>...</footer>
</body>

A reviewer says nesting <header> and <footer> inside <article> is invalid HTML5. Are they correct?

Answer: B
HTML5 allows <header> and <footer> inside any sectioning content elements (<article>, <section>, <aside>, <nav>). They represent the header/footer of that specific section, not the entire page.

↥ back to top

Q39. A <figure> element contains a chart image. Which element should be used to provide a caption that is programmatically associated with the image?

Answer: C
<figcaption> is the correct child element of <figure> for providing a caption. <caption> is used inside <table>, <legend> inside <fieldset>, and <label> with form controls.

↥ back to top

Q40. A developer is unsure whether to use a <div> or <section> for grouping related content. What is the key distinction?

Answer: B
<section> is a thematic grouping element that typically contains a heading and contributes to the document outline. <div> carries no semantic meaning and should be used for purely presentational or scripting groupings.

↥ back to top

8. Responsive Images

Q41. A news site serves hero images. On mobile (viewport ≤ 600 px) it should display a 480 px wide image; on desktop it should display a 1200 px wide image — both in WebP format with JPEG fallbacks. Which HTML5 element is designed for this use case?

Answer: B
<picture> allows specifying multiple <source> elements with media and type conditions. The browser selects the first matching source, enabling both art direction and format selection. srcset alone on <img> handles resolution switching but not art direction or format fallback together.

Example:

<picture>
  <source media="(max-width: 600px)" srcset="hero-small.webp" type="image/webp">
  <source media="(max-width: 600px)" srcset="hero-small.jpg" type="image/jpeg">
  <source srcset="hero-large.webp" type="image/webp">
  <img src="hero-large.jpg" alt="Breaking news hero image">
</picture>
↥ back to top

Q42. A developer writes:

<img src="photo.jpg"
     srcset="photo-480.jpg 480w, photo-800.jpg 800w, photo-1200.jpg 1200w"
     sizes="(max-width: 600px) 100vw, 50vw"
     alt="Mountain landscape">

What does the sizes attribute tell the browser?

Answer: B
sizes describes how wide the image will be rendered at various viewport breakpoints. The browser uses this information together with the device pixel ratio to choose the most appropriate srcset candidate — all before making any network request.

↥ back to top

Q43. An e-commerce page lists product thumbnails. Each thumbnail is always rendered at exactly 200 px wide regardless of viewport. The same image is available at 200 px, 400 px (for 2× Retina), and 600 px (for 3× Retina). Which markup serves the correct resolution to each device?

Answer: A
When the rendered size is fixed, descriptor 2x and 3x (device pixel ratio descriptors) precisely target the correct image for each screen density without needing a sizes attribute.

↥ back to top

Q44. A developer removes the alt attribute entirely from an <img> to save bytes. What is the impact?

Answer: A
Omitting alt is invalid HTML5. Most screen readers fall back to announcing the src URL or filename, which is unhelpful. An empty alt="" is the correct way to mark a decorative image.

↥ back to top

Q45. A developer wants to defer loading of below-the-fold images so they only load when the user scrolls near them, using a native browser feature and no JavaScript library. Which attribute enables this?

Answer: B
The loading="lazy" attribute instructs the browser to defer loading the image until it is near the viewport. It is a native HTML attribute requiring zero JavaScript.

Example:

<!-- Hero image — load immediately -->
<img src="hero.jpg" loading="eager" alt="Hero banner">

<!-- Below-the-fold images — load lazily -->
<img src="card1.jpg" loading="lazy" alt="Card 1">
<img src="card2.jpg" loading="lazy" alt="Card 2">
↥ back to top

9. Web APIs

Q46. A ride-sharing app needs the user's current GPS coordinates. The user's browser supports the HTML5 Geolocation API. Which JavaScript call correctly retrieves the position once?

Answer: B
navigator.geolocation.getCurrentPosition() is the standard HTML5 API call. It requires user permission and invokes successCallback with a GeolocationPosition object, or errorCallback on failure.

Example:

<button onclick="getLocation()">Find Me</button>
<p id="output"></p>

<script>
  function getLocation() {
    if (!navigator.geolocation) {
      document.getElementById('output').textContent = 'Geolocation not supported.';
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        document.getElementById('output').textContent =
          `Lat: ${pos.coords.latitude}, Lng: ${pos.coords.longitude}`;
      },
      (err) => {
        document.getElementById('output').textContent = `Error: ${err.message}`;
      }
    );
  }
</script>
↥ back to top

Q47. A project management app allows users to drag tasks between columns. A developer implements drag-and-drop using the HTML5 Drag and Drop API. Which event on the drop target must call event.preventDefault() to allow a drop?

Answer: C
By default, most elements do not accept drops. Calling event.preventDefault() inside the dragover handler signals to the browser that this element is a valid drop target, enabling the drop event to fire.

Example:

<div id="task" draggable="true" ondragstart="drag(event)">Task A</div>
<div id="column" ondragover="allowDrop(event)" ondrop="drop(event)">
  Drop here
</div>

<script>
  function allowDrop(e) { e.preventDefault(); }          // required!
  function drag(e)      { e.dataTransfer.setData('text', e.target.id); }
  function drop(e) {
    e.preventDefault();
    const id = e.dataTransfer.getData('text');
    e.target.appendChild(document.getElementById(id));
  }
</script>
↥ back to top

Q48. A data-processing web app runs a complex sorting algorithm that freezes the UI for several seconds. A colleague suggests moving it to a Web Worker. What is the primary benefit?

Answer: B
Web Workers operate on a separate OS thread. Because they cannot touch the DOM, the main thread remains free to handle user events and rendering, preventing UI freezes.

Example:

<!-- main.html -->
<script>
  const worker = new Worker('sorter.js');
  worker.postMessage({ data: [5, 3, 1, 4, 2] });
  worker.onmessage = (e) => console.log('Sorted:', e.data.result);
</script>
// sorter.js  (Web Worker script — no DOM access)
self.onmessage = function (e) {
  const sorted = e.data.data.slice().sort((a, b) => a - b);
  self.postMessage({ result: sorted });
};
↥ back to top

Q49. A financial trading dashboard streams live price updates from a server. The connection must remain open and push data to the client continuously. Which HTML5 API is purpose-built for this one-way server-to-client streaming?

Answer: C
EventSource (Server-Sent Events) is designed for one-way, server-to-client streaming over HTTP. It automatically reconnects on disconnect and supports event IDs. WebSockets are bidirectional and more appropriate when the client also needs to push data to the server.

Example:

// Client
const source = new EventSource('/prices');
source.addEventListener('price-update', (e) => {
  const { symbol, price } = JSON.parse(e.data);
  updateUI(symbol, price);
});
source.onerror = () => console.warn('Connection lost, retrying…');
// Server (PHP) — sse_prices.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while (true) {
    echo "event: price-update\n";
    echo 'data: {"symbol":"AAPL","price":' . rand(150, 200) . "}\n\n";
    ob_flush(); flush();
    sleep(1);
}
↥ back to top

Q50. A developer uses the HTML5 History API to build a single-page application with bookmarkable URLs. After calling history.pushState({ page: 2 }, '', '/products'), the user clicks the browser's Back button. Which event fires and where can the state be retrieved?

Answer: B
Clicking Back/Forward after pushState/replaceState fires the popstate event on window. The state object passed to pushState is available as event.state.

Example:

// Navigate programmatically
document.getElementById('nextPage').addEventListener('click', () => {
  history.pushState({ page: 2 }, '', '/products');
  renderPage(2);
});

// Handle browser back/forward
window.addEventListener('popstate', (e) => {
  if (e.state) renderPage(e.state.page);
});
↥ back to top

10. Custom Data Attributes

Q51. A developer stores product IDs on list items using the data-* attribute pattern:

<li data-product-id="SKU-9821" data-category="electronics">Laptop</li>

How is data-product-id accessed in JavaScript?

Answer: C
getAttribute('data-product-id') returns the raw attribute value. element.dataset.productId uses the DOMStringMap API which automatically converts data-product-id (kebab-case) to productId (camelCase). Both are valid.

Example:

<ul>
  <li id="item" data-product-id="SKU-9821" data-category="electronics">Laptop</li>
</ul>
<script>
  const el = document.getElementById('item');
  console.log(el.getAttribute('data-product-id')); // "SKU-9821"
  console.log(el.dataset.productId);               // "SKU-9821"
  console.log(el.dataset.category);                // "electronics"
</script>
↥ back to top

Q52. A team stores sensitive user data such as credit card numbers in data-* attributes to pass them around the DOM. A security reviewer objects. Who is correct, and why?

Answer: B
data-* attributes are visible in the page source and fully accessible via JavaScript. Storing sensitive data there exposes it to XSS attacks. Sensitive data should never be embedded in the DOM.

↥ back to top

Q53. A developer uses CSS to style a button differently based on its state using a data-* attribute. Which CSS selector targets a button where data-state="active"?

Answer: B
CSS attribute selectors ([attr="value"]) work with data-* attributes just like any other HTML attribute.

Example:

<button data-state="inactive" id="btn">Toggle</button>
<style>
  button[data-state="active"]   { background: green; color: white; }
  button[data-state="inactive"] { background: grey; }
</style>
<script>
  document.getElementById('btn').addEventListener('click', function () {
    this.dataset.state = this.dataset.state === 'active' ? 'inactive' : 'active';
  });
</script>
↥ back to top

Q54. A developer needs to store a multi-word string "free shipping" in a data-* attribute and retrieve it via dataset. What is the correct attribute name so that element.dataset.shippingType returns "free shipping"?

Answer: B
The Dataset API converts data- attribute names from kebab-case to camelCase: data-shipping-typedataset.shippingType. Uppercase letters in the attribute name are not allowed per the HTML5 specification.

↥ back to top

Q55. A developer writes a tooltip library that reads the tooltip text from a data-tooltip attribute and creates a <div> dynamically. The text is inserted with innerHTML. A colleague warns this is dangerous. What is the correct fix?

Answer: B
innerHTML interprets the string as HTML, so a crafted data-tooltip value like <img onerror="stealCookies()"> would execute malicious code. Always use textContent for plain text or a trusted sanitiser for HTML.

Example:

// Unsafe
tooltip.innerHTML = element.dataset.tooltip;

// Safe
tooltip.textContent = element.dataset.tooltip;
↥ back to top

11. Meta & Document Head

Q56. A mobile web app's layout looks zoomed-out on smartphones, showing the desktop-sized page scaled down. Which <meta> tag instructs the browser to match the device's screen width and set the initial zoom to 100%?

Answer: B
The viewport meta tag is the standard way to control how the browser scales and sizes the page on mobile devices. width=device-width matches the physical screen width; initial-scale=1 sets 1:1 zoom.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Responsive Page</title>
</head>
<body>...</body>
</html>
↥ back to top

Q57. A developer wants to load a third-party analytics script without blocking HTML parsing, but the script depends on the fully parsed DOM. Which <script> attribute should be used?

Answer: B
defer downloads the script in parallel with HTML parsing and executes it in order after the document is fully parsed, but before DOMContentLoaded. async also downloads in parallel but executes immediately when ready, potentially before parsing is complete.

Example:

<head>
  <!-- Parsed after DOM is ready, in document order -->
  <script src="analytics.js" defer></script>

  <!-- Parsed as soon as downloaded, order not guaranteed -->
  <script src="widget.js" async></script>
</head>
↥ back to top

Q58. A developer wants to hint to the browser to establish a connection to https://api.example.com early — before any actual fetch is made — to reduce latency. Which <link> relationship achieves this?

Answer: C
rel="preconnect" instructs the browser to perform the DNS lookup, TCP handshake, and TLS negotiation with the target origin early. rel="dns-prefetch" only resolves the DNS without establishing the full connection.

Example:

<head>
  <!-- Full connection (DNS + TCP + TLS) -->
  <link rel="preconnect" href="https://api.example.com">

  <!-- DNS only — lightweight fallback for older browsers -->
  <link rel="dns-prefetch" href="https://api.example.com">
</head>
↥ back to top

Q59. A developer sets the following <meta> tag to prevent search engines from indexing a staging site:

<meta name="robots" content="noindex, nofollow">

A colleague says this is unreliable because Google can still index the page. Under what condition is the colleague correct?

Answer: C
If robots.txt blocks crawling, the bot never reads the meta tag but may still list the URL in search results based on link signals. The robust solution is no robots.txt block (so the bot can read the tag) combined with noindex — or use HTTP authentication to restrict access entirely.

↥ back to top

Q60. A developer wants shareable links to their news article to show a rich preview card (title, description, image) when posted on social media. Which set of <meta> tags is responsible for this?

Answer: B
Open Graph protocol (og:*) meta tags are the standard adopted by most social platforms (Facebook, LinkedIn, WhatsApp, Slack) to generate link preview cards. Twitter additionally supports its own twitter:* card tags, but most platforms fall back to Open Graph.

Example:

<head>
  <meta property="og:type"        content="article">
  <meta property="og:title"       content="HTML5 Best Practices in 2026">
  <meta property="og:description" content="A deep dive into modern HTML5 features.">
  <meta property="og:image"       content="https://example.com/preview.jpg">
  <meta property="og:url"         content="https://example.com/html5-guide">

  <!-- Twitter Card fallback -->
  <meta name="twitter:card"       content="summary_large_image">
  <meta name="twitter:title"      content="HTML5 Best Practices in 2026">
  <meta name="twitter:image"      content="https://example.com/preview.jpg">
</head>
↥ back to top

12. SVG

Q61. A company logo must remain crisp at every screen resolution and be styleable with CSS (colour changes on hover). A developer is choosing between embedding the logo as a PNG, a <canvas> drawing, or inline SVG. Which approach is best suited?

Answer: C
Inline SVG embeds the SVG DOM directly into the HTML document, making individual paths and shapes targetable by CSS and JavaScript. An <img src="logo.svg"> is resolution-independent but its internals are isolated and cannot be styled by the page's CSS. PNG is raster-based and pixelates at high DPR. <canvas> is pixel-based and not resolution-independent without manual DPR scaling.

↥ back to top

Q62. An icon library defines reusable SVG shapes with <symbol> and references them with <use>. A developer writes:

<svg style="display:none">
  <symbol id="icon-bell" viewBox="0 0 24 24">
    <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2z"/>
    <path d="M18 16v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/>
  </symbol>
</svg>

<svg aria-label="Notifications" role="img"><use href="#icon-bell"></use></svg>

What is the primary benefit of this pattern?

Answer: B
The <symbol> + <use> pattern is an SVG sprite technique. The shape is defined once inside a hidden <svg>, and <use href="#id"> clones it wherever needed, eliminating markup repetition. viewBox on <symbol> still needs to be set for correct scaling.

↥ back to top

Q63. A developer embeds an SVG with the following viewBox:

<svg viewBox="0 0 100 50" width="400" height="200">
  <rect x="0" y="0" width="100" height="50" fill="steelblue"/>
</svg>

What does viewBox="0 0 100 50" define?

Answer: B
viewBox="min-x min-y width height" establishes the internal coordinate system. The SVG engine maps the 100×50 unit canvas onto the 400×200 px element, scaling all child elements automatically. This is what makes SVGs resolution-independent.

↥ back to top

Q64. A developer compares two approaches for displaying a search icon button:

<!-- A -->
<button>
  <img src="search.svg" alt="Search">
</button>

<!-- B -->
<button aria-label="Search">
  <svg aria-hidden="true" focusable="false" viewBox="0 0 24 24">
    <path d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z"/>
  </svg>
</button>

Which approach is preferred and why?

Answer: B
With inline SVG, aria-hidden="true" prevents screen readers from announcing SVG internals (paths, groups) and focusable="false" prevents IE/Edge from placing focus on the SVG itself. The button's aria-label provides the single, clear accessible name. Approach A works but provides less control over how assistive technology announces the icon.

↥ back to top

Q65. A developer adds a CSS animation to an inline SVG path to draw a loading spinner. The animation uses stroke-dashoffset. Which statement correctly describes SVG versus Canvas for this scenario?

Answer: B
SVG shapes are DOM elements, so CSS properties like stroke-dasharray, stroke-dashoffset, opacity, and transform can be animated with CSS or the Web Animations API. Canvas draws pixels with no persistent DOM nodes, so animations require imperative JavaScript redraws each frame.

↥ back to top

13. WebSocket API

Q66. A multiplayer game needs the server to push position updates to all connected players, and each player's browser must simultaneously send its own position back to the server — all in real time with minimal latency. Which HTML5 API is the correct choice?

Answer: C
WebSocket is the only option that allows simultaneous, low-latency, bidirectional data flow. EventSource is one-way (server → client only). keepalive fetch is for request persistence, not streaming. Long polling has high latency and overhead.

↥ back to top

Q67. A WebSocket client connects using ws://chat.example.com/socket. A security engineer flags the connection as insecure. What is the correct fix and why?

Answer: A
ws:// transmits data in plain text; wss:// (WebSocket Secure) wraps the connection in TLS — the same protocol used by HTTPS. It is mandatory on HTTPS pages (browsers block mixed-content ws:// connections from secure origins).

Example:

// Insecure — avoid on production
const unsafeSocket = new WebSocket('ws://chat.example.com/socket');

// Secure — always use in production
const socket = new WebSocket('wss://chat.example.com/socket');
↥ back to top

Q68. A developer opens a WebSocket and needs to handle incoming messages, connection errors, and clean closure. Which set of event handlers covers all three?

Answer: B
The four WebSocket events are onopen (connection established), onmessage (data received), onerror (connection error), and onclose (connection closed). To handle incoming messages, errors, and closure, you need onmessage, onerror, and onclose.

Example:

const socket = new WebSocket('wss://example.com/ws');

socket.onopen    = ()  => console.log('Connected');
socket.onmessage = (e) => console.log('Received:', e.data);
socket.onerror   = (e) => console.error('Error:', e);
socket.onclose   = (e) => console.log('Closed, code:', e.code);
↥ back to top

Q69. A developer sends an object over a WebSocket:

const socket = new WebSocket('wss://example.com/ws');
socket.onopen = () => {
  socket.send({ type: 'chat', text: 'Hello!' });
};

What is the actual data received by the server?

Answer: B
WebSocket.send() accepts string, Blob, ArrayBuffer, or ArrayBufferView. Passing a plain object invokes .toString(), yielding "[object Object]". Always use JSON.stringify() for structured data.

Example:

// Wrong
socket.send({ type: 'chat', text: 'Hello!' }); // sends "[object Object]"

// Correct
socket.send(JSON.stringify({ type: 'chat', text: 'Hello!' }));

// Receiving
socket.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  console.log(msg.type, msg.text);
};
↥ back to top

Q70. A WebSocket-based chat app sends the user's session token as a query parameter: wss://example.com/ws?token=eyJhbGci.... A security reviewer objects. What is the primary concern and the recommended alternative?

Answer: B
Even over TLS, URLs (including query strings) are recorded in server logs, proxy logs, and browser history. Sensitive tokens in URLs are a known OWASP risk. The safer pattern is to exchange a short-lived, opaque ticket via a secure HTTPS endpoint and pass that ticket as the first WebSocket message, or use cookies with HttpOnly and Secure flags for authentication.

↥ back to top

14. IFrame & Sandbox

Q71. A content management platform embeds third-party widgets using <iframe>. A security auditor recommends adding the sandbox attribute with no value:

<iframe src="https://widget.example.com" sandbox></iframe>

What restrictions does a value-less sandbox apply?

Answer: B
A bare sandbox attribute applies the maximum restriction set: scripts disabled, forms blocked, popups blocked, plugins blocked, same-origin access denied, and top-level navigation prevented. Each capability must be explicitly re-enabled with a allow-* token.

↥ back to top

Q72. An embedded payment iframe must be able to submit a form but must not be allowed to run JavaScript or open popups. Which sandbox value is correct?

Answer: B
allow-forms re-enables form submission while keeping scripts and popups blocked (the default sandbox behaviour). Adding allow-scripts would permit JavaScript execution, which is not desired here.

↥ back to top

Q73. A developer adds sandbox="allow-scripts allow-same-origin" to an iframe loading content from the same origin as the parent page. A colleague warns this is dangerous. Why?

Answer: B
allow-same-origin grants the iframe the same origin as the parent, giving it access to the parent's storage and DOM. allow-scripts lets it run JavaScript. Together, a script inside the iframe can call parent.document.body.innerHTML = '' or steal cookies — negating all sandbox protections. This combination should be avoided for same-origin embedded content.

↥ back to top

Q74. A media article embeds dozens of YouTube iframes below the fold. Page load performance is poor because all iframes load immediately. Which HTML5 attribute defers iframe loading until the user scrolls near them, with no JavaScript required?

Answer: C
The loading="lazy" attribute, supported natively on <iframe> as well as <img>, instructs the browser to defer loading until the element is near the viewport. No JavaScript or Intersection Observer is needed.

Example:

<!-- Loads immediately (above-the-fold embed) -->
<iframe src="https://www.youtube.com/embed/abc123"
        title="Intro video"
        loading="eager"
        allowfullscreen></iframe>

<!-- Deferred until near viewport -->
<iframe src="https://www.youtube.com/embed/xyz789"
        title="Related video"
        loading="lazy"
        allowfullscreen></iframe>
↥ back to top

15. Progress, Meter, Time & Dialog

Q75. A file upload UI must show a progress bar that reflects the percentage of bytes uploaded. While the upload is in progress but the total size is unknown, the bar should display an animated indeterminate state. Which markup produces the indeterminate state?

Answer: B
A <progress> element without a value attribute renders in an indeterminate state (typically an animated looping bar). Once the total size is known, setting value and max switches it to a determinate percentage display.

Example:

<!-- Indeterminate — total unknown -->
<progress></progress>

<!-- Determinate — 60 % complete -->
<progress value="60" max="100"></progress>
↥ back to top

Q76. A server dashboard shows disk usage. The developer must choose between <progress> and <meter> for the display. The disk is 60 % full — considered high but not critical; values above 80 % are dangerous. Which element is semantically correct and which attributes communicate the threshold levels?

Answer: B
<meter> is designed for scalar gauge measurements (disk space, temperature, score) within a known range. Its low, high, and optimum attributes let browsers colour-code the bar (green/yellow/red). <progress> is designed for task completion and does not support threshold attributes.

Example:

<label for="disk">Disk usage:</label>
<meter id="disk" value="60" min="0" max="100"
       low="50" high="80" optimum="20">60 GB of 100 GB used</meter>
↥ back to top

Q77. A news article displays its publication date as "April 13, 2026". A developer wants search engines and screen readers to interpret the date programmatically. Which markup is correct?

Answer: C
The <time> element semantically marks up dates and times. The datetime attribute provides a machine-readable value in a standard format (ISO 8601 for dates). This enables search engines to display rich snippets and assistive technologies to surface date information accurately.

Example:

<article>
  <h2>HTML5 in 2026</h2>
  <p>Published on <time datetime="2026-04-13">April 13, 2026</time></p>
  <p>Event starts at <time datetime="2026-04-13T09:00:00+05:30">9:00 AM IST</time></p>
</article>
↥ back to top

Q78. A mortgage calculator form has two number inputs (principal and rate) and must display the computed monthly payment in a read-only field that is semantically associated with the form. Which HTML5 element is purpose-built for this?

Answer: C
<output> is an HTML5 element specifically designed to display the result of a calculation or user action. Its for attribute takes a space-separated list of input element IDs, establishing a programmatic relationship between inputs and their computed result.

Example:

<form oninput="payment.value = (principal.valueAsNumber * rate.valueAsNumber / 1200).toFixed(2)">
  <label>Principal: <input type="number" id="principal" name="principal" value="100000"></label>
  <label>Rate (%): <input type="number" id="rate" name="rate" step="0.01" value="6"></label>
  <label>Monthly payment: <output name="payment" for="principal rate">0.00</output></label>
</form>
↥ back to top

Q79. A developer includes the following in the HTML:

<template id="card-tpl">
  <div class="card">
    <h2 class="card-title"></h2>
    <p class="card-body"></p>
  </div>
</template>

Which statement correctly describes the <template> element?

Answer: B
Content inside <template> is inert: it is parsed into a DocumentFragment stored in template.content, but it is not rendered, images are not fetched, scripts are not run, and the content is isolated from the main document until explicitly cloned with document.importNode() or template.content.cloneNode(true).

Example:

const tpl   = document.getElementById('card-tpl');
const clone = tpl.content.cloneNode(true);
clone.querySelector('.card-title').textContent = 'HTML5 Templates';
clone.querySelector('.card-body').textContent  = 'Reusable markup patterns.';
document.getElementById('container').appendChild(clone);
↥ back to top

Q80. A web app needs a modal confirmation dialog. Previously the team used a <div> overlay with ARIA roles. HTML5.2 introduced a native element for this. Which element and method correctly open a modal dialog that traps focus and adds an ::backdrop overlay?

Answer: B
HTMLDialogElement.showModal() opens the dialog as a modal: it sits on the top layer above all other content, a ::backdrop pseudo-element darkens the page, and the browser constrains Tab/Shift+Tab focus to elements inside the dialog. show() opens it as a non-modal (no backdrop, no focus trap). <modal> is not a valid HTML element.

Example:

<button id="open-btn">Delete Account</button>

<dialog id="confirm-dialog">
  <h2>Confirm Deletion</h2>
  <p>This action cannot be undone.</p>
  <button id="cancel-btn">Cancel</button>
  <button id="confirm-btn">Delete</button>
</dialog>

<script>
  const dialog    = document.getElementById('confirm-dialog');
  const openBtn   = document.getElementById('open-btn');
  const cancelBtn = document.getElementById('cancel-btn');

  openBtn.addEventListener('click',   () => dialog.showModal());
  cancelBtn.addEventListener('click', () => dialog.close());
</script>
↥ back to top