Turning Learners Into Developers
Codekilla
CODEKILLA
HTML

HTML Interview Questions and Answers (2026 Edition)

Top 30 HTML interview questions with model answers, code examples and a quick revision table.

← Interview Questions

HTML Fundamentals & Structure

1. What is HTML5 and how does it differ from previous HTML versions?

HTML5 is the fifth and current major version of HTML, designed to improve the web's capabilities by supporting multimedia, offline storage, and mobile applications without the need for plugins. Key differences from earlier versions include new semantic elements like <article>, <section>, <nav>, and <aside> for better document structure. It introduced native audio and video support (<audio>, <video>), canvas for drawing graphics, geolocation, web storage (localStorage, sessionStorage), and Web Sockets for real-time communication. HTML5 simplifies the DOCTYPE declaration and emphasizes better error handling and cross-browser compatibility.

2. Explain the difference between an HTML element and an HTML tag.

An HTML tag is a keyword enclosed in angle brackets, like <div> or <p>. Tags are used to mark the beginning and end of an element. Most tags come in pairs (an opening tag and a closing tag), but some are self-closing (e.g., <img />, <br />). An HTML element consists of the opening tag, its attributes, the content between the tags, and the closing tag. For instance, <p>This is content.</p> is a paragraph element, where <p> is the opening tag, </p> is the closing tag, and "This is content." is the content.

3. What is the DOCTYPE declaration and why is it important in HTML5?

The <!DOCTYPE html> declaration is a mandatory preamble for an HTML document. It informs the web browser about the document type and version of HTML being used. In HTML5, the declaration is remarkably simple, reflecting a shift towards less strict, more forgiving parsing. Its importance lies in ensuring standards mode rendering across all browsers, preventing them from falling into "quirks mode." Quirks mode can cause inconsistent rendering due to emulation of outdated browser behaviors. By declaring the DOCTYPE, you guarantee that the browser interprets and renders your HTML document according to modern web standards.

4. What is Semantic HTML and why is it crucial for modern web development?

Semantic HTML uses specific HTML5 elements to convey meaning about the content they contain, rather than just presenting it visually. For example, <header>, <nav>, <article>, <section>, <aside>, and <footer> are semantic tags. This is crucial because it makes webpages more accessible to assistive technologies (like screen readers), improves SEO by helping search engines understand content hierarchy, and makes code more readable and maintainable for developers. Non-semantic elements like <div> and <span> convey no inherent meaning about their content.

html
<header>
    <h1>Website Title</h1>
    <nav>
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
        </ul>
    </nav>
</header>
<main>
    <article>
        <h2>Article Title</h2>
        <p>Article content goes here...</p>
    </article>
</main>
<footer>
    <p>&copy; 2026 My Website</p>
</footer>

5. Differentiate between block-level and inline elements in HTML. Provide examples.

Block-level elements occupy the full available width and typically start on a new line. They can contain other block-level or inline elements. Examples include <div>, <p>, <h1> to <h6>, <ul>, <ol>, <li>, <form>, <header>, <footer>, <section>, <article>. Inline elements only occupy the width required by their content and do not start on a new line. They can only contain other inline elements or plain text. Examples include <span>, <a>, <strong>, <em>, <img>, <input>, <label>, <button>.

html
<!-- Block-level example -->
<p>This is a paragraph.</p>
<div>This is a division.</div>

<!-- Inline example -->
<span>This is inline text.</span>
<a href="#">This is a link.</a>

6. Explain the role of HTML attributes and give examples of global attributes.

HTML attributes provide additional information about an element, modifying its default behavior or appearance. They are placed within the opening tag of an element, typically as name="value" pairs. Attributes are essential for defining element-specific properties, linking resources, or enabling interactivity. Global attributes are those that can be applied to any HTML element. Common global attributes include:

  • id: Specifies a unique identifier for an element.
  • class: Assigns one or more class names for styling or scripting.
  • style: Applies inline CSS styles.
  • title: Provides advisory information about the element (often displayed as a tooltip).
  • data-*: Custom data attributes for storing arbitrary data.
  • tabindex: Defines the tab order of an element.
  • lang: Specifies the language of the element's content.

Forms, Media & Interactivity

7. Describe the purpose of the <form> element and list some important input types introduced in HTML5.

The <form> element is used to create an interactive area where users can input data, which is then sent to a server for processing. It acts as a container for various form controls like input fields, checkboxes, radio buttons, and submission buttons. Key attributes include action (where to send the data), method (HTTP method like GET or POST), and enctype (how the data should be encoded). HTML5 introduced several new and useful input types:

  • type="email": For email addresses, providing basic client-side validation.
  • type="url": For URLs, also with client-side validation.
  • type="number": For numerical input, often with spinner controls.
  • type="date", type="time", type="datetime-local": For date and time selection.
  • type="range": For selecting a numerical value within a specified range (slider).
  • type="search": For search fields, often styled differently by browsers.
  • type="tel": For telephone numbers.
html
<form action="/submit-form" method="post">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <label for="quantity">Quantity:</label>
    <input type="number" id="quantity" name="quantity" min="1" max="10">

    <button type="submit">Submit</button>
</form>

8. When would you use the <img> tag versus setting an image with CSS background-image?

Use the <img> tag when the image is content-critical and part of the document's information. This includes product photos, user avatars, or diagrams essential for understanding the text. <img> tags are accessible (with alt text), part of the DOM, and can be optimized for SEO. Use CSS background-image when the image is purely decorative or for styling purposes, like a background pattern, an icon, or a visual element that doesn't convey essential meaning to the content. Background images don't load in screen readers, don't impact SEO directly, and offer powerful CSS controls for positioning and repetition.

9. How do <audio> and <video> tags enhance multimedia on the web?

The <audio> and <video> tags provide native browser support for embedding and playing media files directly in HTML, eliminating the need for third-party plugins like Flash. They offer a standardized API for controlling playback (play, pause, volume), seeking, and handling events. Key attributes include src (path to media file), controls (displays browser's default controls), autoplay, loop, preload, and poster (for video). Multiple <source> elements can be included within these tags to offer different file formats (e.g., MP4, WebM, Ogg) for broader browser compatibility.

html
<video controls width="640" height="360" poster="thumbnail.jpg">
    <source src="video.mp4" type="video/mp4">
    <source src="video.webm" type="video/webm">
    <p>Your browser does not support the video tag.</p>
</video>

10. Explain the concept of data-* attributes and their practical application.

data-* attributes are custom data attributes that allow developers to embed custom, non-standard attributes on any HTML element. The * can be replaced by any valid string that doesn't contain uppercase letters and is prefixed with data-. Their primary purpose is to store extra information about an element that is private to the page or application, and not intended for public consumption by search engines or other software. This data can then be easily accessed and manipulated using JavaScript. Common applications include storing IDs, configuration options, state information, or values for dynamic content updates without relying on non-semantic attributes like id or class.

html
<button data-product-id="123" data-price="29.99" class="add-to-cart">Add to Cart</button>

<script>
    document.querySelector('.add-to-cart').addEventListener('click', function(event) {
        const productId = event.target.dataset.productId; // '123'
        const price = event.target.dataset.price;       // '29.99'
        console.log(`Adding product ${productId} with price ${price} to cart.`);
    });
</script>

11. Discuss the pros and cons of using <iframe> elements.

The <iframe> element is used to embed another HTML document within the current HTML document. Pros:

  • Content Isolation: Embedded content runs in an isolated environment, preventing scripts from interfering with the parent page.
  • Third-party Content: Ideal for embedding external content like maps, ads, or videos (YouTube, Vimeo).
  • Security Sandboxing: The sandbox attribute offers granular control over the iframe's capabilities, enhancing security.
  • Modular Design: Allows for loading components dynamically from different sources. Cons:
  • Security Risks: Without proper sandboxing, cross-site scripting (XSS) or clickjacking attacks are possible.
  • Performance Overhead: Each iframe loads a separate document, consuming additional memory and network resources, potentially slowing down the page.
  • SEO Challenges: Search engines might struggle to properly index content within iframes.
  • Accessibility: Can be challenging for assistive technologies if not implemented carefully.
  • Responsiveness: Making iframes responsive across devices can be tricky.

Accessibility, SEO & Performance

12. What are ARIA attributes and how do they improve web accessibility?

ARIA (Accessible Rich Internet Applications) attributes are a set of special attributes you can add to HTML elements to provide additional semantics and describe the roles, states, and properties of UI components that aren't natively available in HTML. They don't change the element's visual appearance or behavior, but they provide critical information to assistive technologies like screen readers. This allows users with disabilities to better understand and interact with complex web content, such as custom widgets (accordions, carousels, tabs) or dynamic updates, making the web more inclusive.

html
<button aria-expanded="false" aria-controls="menu-dropdown">
    Menu
</button>
<div id="menu-dropdown" role="menu" hidden>
    <a href="#" role="menuitem">Item 1</a>
    <a href="#" role="menuitem">Item 2</a>
</div>

13. Explain the importance of the alt attribute for <img> tags.

The alt (alternative text) attribute for the <img> tag is crucial for web accessibility and SEO. Its primary purpose is to provide a textual description of the image content. For accessibility, screen readers vocalize this text to visually impaired users, allowing them to understand the image's purpose and content. Without it, images are skipped, making the content less accessible. For SEO, search engines use alt text to understand the image's context, which can improve image search rankings and overall page relevance. If an image fails to load, the alt text is displayed in its place. For purely decorative images, alt="" (an empty string) can be used to signal to screen readers that the image can be ignored.

14. How do meta tags contribute to SEO and proper rendering?

Meta tags are HTML tags that provide metadata about an HTML document. While not displayed on the page, they are parsed by browsers and search engines. For SEO, meta name="description" provides a brief summary for search results, and meta name="keywords" (though less impactful now) offers terms related to content. Open Graph (og:) and Twitter Card (twitter:) meta tags are crucial for how content appears when shared on social media. For proper rendering, meta charset="UTF-8" defines character encoding, preventing display issues. meta name="viewport" is essential for responsive design, controlling how the browser renders the page on different screen sizes by setting width and initial scale.

html
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="A comprehensive guide to HTML interview questions for 2026.">
    <meta property="og:title" content="HTML Interview Prep">
</head>

15. What is the <picture> element and how does it help with responsive images?

The <picture> element provides a solution for responsive images by allowing developers to specify multiple image sources for different display conditions. It acts as a wrapper for multiple <source> elements and one <img> element. Each <source> element specifies a media query (e.g., media="(min-width: 768px)") or a type attribute (e.g., type="image/webp") along with an srcset attribute referencing one or more image files. The browser evaluates the <source> elements and chooses the most appropriate image based on the current viewport size, screen resolution, or supported image format. The <img> element serves as a fallback for browsers that don't support <picture> or if no <source> matches. This ensures optimal image delivery, improving performance and user experience.

html
<picture>
    <source srcset="large.webp" type="image/webp" media="(min-width: 1000px)">
    <source srcset="medium.webp" type="image/webp" media="(min-width: 600px)">
    <img src="small.jpg" alt="Description of the image">
</picture>

16. Explain the difference between defer and async attributes for <script> tags.

Both defer and async attributes are used on external JavaScript files to prevent blocking HTML parsing, but they differ in execution order.

Featureasyncdefer
DownloadAsynchronous (parallel to HTML parsing)Asynchronous (parallel to HTML parsing)
ExecutionAsynchronous, immediately after downloadAfter HTML parsing is complete, in order
Blocking HTMLNo (but can block DOMContentLoaded event)No
OrderNot guaranteed (executes as soon as available)Guaranteed (executes in the order they appear)
Use CaseIndependent scripts (e.g., analytics, ads)Scripts dependent on DOM or other scripts

async scripts execute as soon as they are downloaded, potentially out of order. defer scripts download in parallel but execute in the order they appear in the document, after HTML parsing is complete but before the DOMContentLoaded event.

html
<script src="script1.js" async></script>
<script src="script2.js" defer></script>
<script src="script3.js" defer></script> <!-- script2.js will execute before script3.js -->

17. How can you implement lazy loading for images and iframes in HTML?

Lazy loading defers the loading of non-critical resources (like images or iframes) until they are needed, typically when they enter the user's viewport. This significantly improves initial page load time and reduces bandwidth usage. HTML provides a native loading attribute for this:

  • loading="lazy": The browser will defer loading the resource until it is close to the viewport.
  • loading="eager": The browser loads the resource immediately (default behavior).
  • loading="auto": The browser decides whether to lazy-load based on its own heuristics.

For images:

html
<img src="placeholder.jpg" data-src="actual-image.jpg" alt="A beautiful landscape" loading="lazy">

For iframes:

html
<iframe src="external-content.html" title="Embedded content" loading="lazy"></iframe>

For older browsers without native support, JavaScript Intersection Observer API can be used to detect when elements become visible, then replace data-src with src.

Advanced Concepts & APIs

18. Compare and contrast localStorage, sessionStorage, and IndexedDB for client-side storage.

FeaturelocalStoragesessionStorageIndexedDB
ScopeOrigin (domain)Origin and session (tab/window)Origin
PersistencePersistent (until explicitly cleared)Cleared when the browser tab/window closesPersistent (until explicitly deleted)
Capacity~5-10 MB~5-10 MBSignificantly larger (hundreds of MB to GBs)
Data TypeString-only (requires JSON.stringify/parse)String-only (requires JSON.stringify/parse)Stores structured data (objects, files)
APISynchronous, simple key-valueSynchronous, simple key-valueAsynchronous, indexed, transactional, object-oriented
Use CaseUser preferences, login state, offline dataSession-specific data (form inputs, temporary state)Complex offline data, large datasets, PWA

19. What are Web Workers and when would you use them?

Web Workers allow JavaScript to run in the background, in a separate thread, without interfering with the main thread (where the UI renders). This prevents long-running scripts from making the user interface unresponsive. You would use Web Workers for CPU-intensive tasks that could block the main thread, such as:

  • Heavy computations (e.g., complex calculations, data processing).
  • Image manipulation.
  • Processing large data sets.
  • Spelling checkers, syntax highlighting.
  • Data compression or encryption. Workers communicate with the main thread via messages (postMessage() and onmessage event handlers). They have a restricted DOM access and cannot directly manipulate the UI.
javascript
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ number: 1000000000 }); // Send data to worker

worker.onmessage = function(event) {
    console.log('Result from worker:', event.data);
};

// worker.js
onmessage = function(event) {
    const { number } = event.data;
    let sum = 0;
    for (let i = 0; i < number; i++) {
        sum += i;
    }
    postMessage(sum); // Send result back to main thread
};

20. Differentiate between Server-Sent Events (SSE) and WebSockets. When would you choose one over the other?

FeatureServer-Sent Events (SSE)WebSockets
CommunicationUnidirectional (server to client only)Bidirectional (full-duplex)
ProtocolHTTP/text-based (MIME type text/event-stream)WS protocol (full-duplex TCP connection)
OverheadLower (simple text stream)Higher (frame-based, more complex handshake)
ConnectionLong-lived HTTP connection, automatic reconnectLong-lived, persistent connection
Data TypeText-based eventsText and binary data
Use CasesReal-time feeds (stock tickers, news updates), notifications, simple chat apps (server-driven)Collaborative editing, real-time gaming, complex chat apps, high-frequency updates

Choose SSE for server-driven, one-way data streams where the client only needs to receive updates (e.g., stock price updates, activity feeds). It's simpler to implement and uses standard HTTP. Choose WebSockets for real-time, bidirectional communication where both client and server need to send and receive messages frequently (e.g., multiplayer games, live chat applications, collaborative whiteboards). It offers lower latency and higher throughput for frequent two-way exchanges.

21. What is the difference between Shadow DOM and Virtual DOM?

Shadow DOM is a web standard that provides a way to encapsulate a component's internal HTML, CSS, and JavaScript, isolating it from the main document's DOM. It creates a "shadow tree" that is attached to a "shadow host" element in the main DOM. Styles defined within the shadow DOM are scoped to it, preventing leakage and conflicts. It's fundamental to Web Components for creating reusable and encapsulated UI widgets. Virtual DOM is a programming concept, primarily used by libraries like React and Vue, where a lightweight representation of the actual DOM is kept in memory. When state changes, these libraries first update the Virtual DOM, then efficiently calculate the minimal differences (diffing algorithm) between the new and old Virtual DOMs. These changes are then batched and applied to the real DOM, optimizing rendering performance by reducing direct DOM manipulations, which are expensive.

22. Explain the purpose of <template> and <slot> elements in HTML.

The <template> element is used to declare fragments of HTML that are not rendered initially but can be instantiated and cloned at runtime using JavaScript. It's ideal for storing reusable HTML structures, especially for custom elements or dynamic content. Content inside a <template> is inert; scripts within it don't run, images don't load, and styles don't apply until the template is activated. The <slot> element is used within Shadow DOM to create placeholders for content that a user can insert into a Web Component. It enables composition and flexible content distribution. When a Web Component is used, the content placed between its opening and closing tags will be projected into the corresponding <slot> elements within the component's Shadow DOM, allowing for customizable parts of the component.

html
<!-- Using template for reusable content -->
<template id="my-card-template">
    <style> .card { border: 1px solid gray; padding: 10px; } </style>
    <div class="card">
        <h3 part="title"><slot name="card-title">Default Title</slot></h3>
        <p><slot>Default Content</slot></p>
    </div>
</template>

<!-- Usage of a custom element that leverages template and slot -->
<my-custom-card>
    <span slot="card-title">My Awesome Card</span>
    <p>This is the main content for the card.</p>
</my-custom-card>

23. Compare <canvas> and <svg> for graphics rendering in HTML.

Feature<canvas><svg>
TypeBitmap (raster) graphicsVector graphics
DrawingJavaScript API draws pixels onto a canvasDeclarative XML describes shapes and paths
ResolutionResolution-dependent (pixels blur when scaled)Resolution-independent (scales without loss)
DOMA single DOM elementEach shape is a DOM element
InteractivityEvent listeners on the canvas itself (pixel-level hit detection via JS)Event listeners on individual shapes (native hit detection)
EditingProgrammatic via JSText editor, vector graphics software, JS
Use CasesGames, photo editors, complex animations, dynamic chartsLogos, icons, interactive maps, static diagrams, data visualization

Scenario & System Design Questions

24. You're building a responsive navigation bar. Describe the HTML structure and common practices for making it accessible.

For a responsive navigation bar, the HTML typically involves:

  • A <nav> element: Semantically defines a navigation section.
  • An <ul> (unordered list): Contains the navigation links.
  • <li> items: Each list item wraps an individual link.
  • <a> tags: The actual navigation links.
  • A <button> for toggling: For mobile views, this button reveals/hides the navigation. Accessibility practices:
  1. Semantic HTML: Using <nav>, <ul>, <li>, <a> inherently provides good structure.
  2. Toggle Button: For the mobile menu toggle button, use aria-controls to link it to the navigable region, aria-expanded="false" (initially) and aria-expanded="true" (when open), and aria-label="Open navigation" for screen readers.
  3. Keyboard Navigation: Ensure all links are focusable (tabindex can be used if non-interactive elements are given roles, but usually not needed for <a>).
  4. Skip Link: Optionally, include a "Skip to main content" link at the top for keyboard users.
  5. Focus Management: When the menu opens, move focus inside it. When it closes, return focus to the toggle button.
  6. Screen Reader Visibility: Ensure hidden menu items are correctly hidden from screen readers (e.g., display: none or visibility: hidden via CSS, or hidden attribute) until toggled.
html
<nav aria-label="Main navigation">
    <button class="menu-toggle" aria-controls="main-menu" aria-expanded="false">
        Menu
    </button>
    <ul id="main-menu" class="nav-list" role="menu" hidden>
        <li role="none"><a href="/" role="menuitem">Home</a></li>
        <li role="none"><a href="/products" role="menuitem">Products</a></li>
        <li role="none"><a href="/contact" role="menuitem">Contact</a></li>
    </ul>
</nav>

25. How would you structure a typical blog post or article using semantic HTML5 elements?

A typical blog post or article should be structured to convey its meaning clearly to both browsers and assistive technologies using semantic HTML5.

  1. <article>: The main container for the independent, self-contained content (the entire blog post).
  2. <header> (inside <article>): Contains introductory information for the article, such as:
    • <h1>: The article's main title.
    • <address>: Author information.
    • <time>: Publication date (with datetime attribute).
  3. <section>: Used to group related content within the article, e.g., an introduction, body paragraphs, conclusion. Each section could have its own <h2>.
  4. <p>: For paragraphs of text.
  5. <img> or <figure> with <figcaption>: For images, especially if they need captions.
  6. <blockquote>: For quoted text.
  7. <footer> (inside <article>): For post-content information, like related links, tags, or author bio. This structure helps with readability, SEO, and accessibility.
html
<article>
    <header>
        <h1>My Awesome Blog Post Title</h1>
        <p>By <address>John Doe</address> on <time datetime="2026-03-15">March 15, 2026</time></p>
    </header>

    <section>
        <h2>Introduction</h2>
        <p>This is the introductory paragraph of the blog post.</p>
        <figure>
            <img src="blog-image.jpg" alt="Description of the blog image">
            <figcaption>A compelling image related to the article.</figcaption>
        </figure>
    </section>

    <section>
        <h2>Main Content Section</h2>
        <p>Further details and explanations...</p>
        <blockquote>"A well-structured document is a joy to read."</blockquote>
    </section>

    <footer>
        <p>Tags: <a href="/tag/html">HTML</a>, <a href="/tag/web-dev">Web Dev</a></p>
    </footer>
</article>

26. You have an image-heavy webpage. What HTML-specific techniques would you employ to improve its performance and user experience?

To improve performance and UX for an image-heavy page using HTML:

  1. Responsive Images (<picture> or srcset): Use <picture> with multiple <source> elements or the srcset attribute on <img> to serve appropriately sized and formatted images based on screen size and resolution (e.g., WebP for modern browsers, JPEG for fallback). This reduces unnecessary downloads.
  2. Lazy Loading: Implement loading="lazy" on <img> and <iframe> elements to defer loading off-screen content until it's near the viewport.
  3. alt Attributes: Essential for accessibility and SEO, providing context even if images fail to load.
  4. width and height Attributes: Specify explicit width and height on <img> tags to reserve space, preventing Cumulative Layout Shift (CLS) and improving perceived load speed.
  5. preload for LCP Image: Use <link rel="preload" as="image" href="hero-image.jpg"> in the <head> for the Largest Contentful Paint (LCP) image to prioritize its loading.
  6. Image Formats: Choose modern, efficient formats like WebP or AVIF.
  7. decoding="async": Hint to the browser that image decoding can be done asynchronously, preventing main thread blocking.
html
<head>
    <link rel="preload" as="image" href="hero-mobile.webp" media="(max-width: 600px)">
    <link rel="preload" as="image" href="hero-desktop.webp" media="(min-width: 601px)">
</head>
<body>
    <picture>
        <source media="(min-width: 1024px)" srcset="large-hero.webp" type="image/webp">
        <source media="(min-width: 600px)" srcset="medium-hero.webp" type="image/webp">
        <img src="small-hero.jpg" alt="Primary content hero image" loading="lazy" width="800" height="450" decoding="async">
    </picture>
    <!-- More images with loading="lazy" and width/height -->
</body>

27. You need to create a reusable UI component, like a custom button with specific styles and behaviors. How would you leverage HTML's Web Components features?

To create a reusable UI component like a custom button, I'd leverage Web Components:

  1. Custom Elements: Define a new HTML tag (<custom-button>) using customElements.define(). The component's logic and behavior are encapsulated within a JavaScript class that extends HTMLElement.
  2. Shadow DOM: Attach a Shadow DOM to the custom element using this.attachShadow({ mode: 'open' }). This isolates the component's internal structure and styles from the main document, preventing conflicts and ensuring consistent rendering.
  3. HTML <template>: Use a <template> element to define the component's internal HTML structure. This template is then cloned and appended to the Shadow DOM, making the component's rendering efficient.
  4. <slot> Elements: If the custom button needs to accept dynamic content (e.g., text, icons), use <slot> elements within the template. Named slots allow for specific content projection.
  5. Attributes and Properties: Define observed attributes (observedAttributes static getter) to react to changes from the outside world, and use getters/setters for JavaScript properties for programmatic control. This approach ensures encapsulation, reusability, and interoperability of the component.
javascript
// custom-button.js
class CustomButton extends HTMLElement {
    constructor() {
        super();
        const shadow = this.attachShadow({ mode: 'open' });
        const template = document.getElementById('custom-button-template').content.cloneNode(true);
        shadow.appendChild(template);
    }

    connectedCallback() {
        // Add event listeners, etc.
        this.shadowRoot.querySelector('button').addEventListener('click', () => {
            alert('Custom button clicked!');
        });
    }
}
customElements.define('custom-button', CustomButton);
html
<template id="custom-button-template">
    <style>
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
    <button><slot>Default Button Text</slot></button>
</template>

<custom-button>Click Me</custom-button>
<custom-button>Submit Form</custom-button>

28. Describe how you would implement client-side validation for a complex HTML form using built-in HTML features and minimal JavaScript.

For client-side validation, I'd first leverage native HTML5 form validation attributes due to their ease of use, accessibility, and no-JavaScript fallback.

  1. required: Mark essential fields that must be filled.
  2. type attributes: Use specific input types like email, url, number, date, which automatically trigger basic validation for their respective formats.
  3. min, max, minlength, maxlength: For number inputs (range) and text inputs (length constraints).
  4. pattern: Use regular expressions for custom validation rules (e.g., specific phone number formats, alphanumeric codes).
  5. novalidate (on <form>): Only use this if JavaScript handles all validation or if you want to bypass browser validation temporarily for specific scenarios.
  6. aria-describedby and aria-live: For accessibility, link error messages to input fields and make error messages live regions. Minimal JavaScript:
  • Listen for the invalid event on fields to customize error messages (e.g., inputElement.setCustomValidity('Your custom message here');).
  • Listen for the submit event on the form to perform any complex, inter-field validation that HTML attributes cannot handle, and prevent submission if invalid.
  • Clear custom validity messages on input changes (inputElement.setCustomValidity('')).
html
<form novalidate>
    <label for="username">Username (min 3 chars):</label>
    <input type="text" id="username" name="username" required minlength="3">
    <span class="error-message" aria-live="polite"></span>

    <label for="password">Password (8+ chars, incl. number):</label>
    <input type="password" id="password" name="password" required pattern="(?=.*\d).{8,}">
    <span class="error-message" aria-live="polite"></span>

    <button type="submit">Register</button>
</form>

<script>
    const form = document.querySelector('form');
    form.addEventListener('submit', function(event) {
        if (!form.checkValidity()) {
            event.preventDefault(); // Stop form submission if not valid
            // Display custom error messages here if needed
            Array.from(form.elements).forEach(input => {
                if (input.validity.patternMismatch) {
                    input.setCustomValidity('Password must contain at least one number and be 8+ characters long.');
                } else if (input.validity.valueMissing) {
                    input.setCustomValidity('This field is required.');
                } else if (input.validity.tooShort) {
                    input.setCustomValidity(`Please enter at least ${input.minLength} characters.`);
                } else {
                    input.setCustomValidity(''); // Reset validity
                }
                const errorMessageSpan = input.nextElementSibling;
                if (errorMessageSpan && errorMessageSpan.classList.contains('error-message')) {
                    errorMessageSpan.textContent = input.validationMessage;
                }
            });
        }
    });

    // Clear custom validity messages when input changes
    form.addEventListener('input', function(event) {
        if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
            event.target.setCustomValidity('');
            const errorMessageSpan = event.target.nextElementSibling;
            if (errorMessageSpan && errorMessageSpan.classList.contains('error-message')) {
                errorMessageSpan.textContent = '';
            }
        }
    });
</script>

29. You need to embed content from various sources onto your webpage (e.g., a YouTube video, a social media feed, and a simple document). Discuss your options and considerations for each.

For embedding content, I'd consider:

  1. YouTube Video:
    • Option: <iframe>. YouTube provides embed codes using <iframe>.
    • Considerations: Use loading="lazy" for performance. Add title for accessibility. Be mindful of sandbox attributes for security, though YouTube embeds are generally safe. Responsive scaling often requires CSS (aspect-ratio or padding hacks).
    html
    <iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen loading="lazy"></iframe>
    
  2. Social Media Feed (e.g., Twitter, Instagram):
    • Option 1: <iframe> provided by the platform (common for widgets).
    • Option 2: Platform's JavaScript SDK (generates its own HTML/CSS/JS).
    • Considerations: <iframe> means isolated content but can be heavy. SDKs offer more control but introduce external JS dependencies and potential styling conflicts. Both impact performance. Ensure privacy and GDPR compliance, especially with third-party tracking. loading="lazy" can help with iframes.
  3. Simple Document (e.g., PDF, another HTML file):
    • Option 1: <iframe>: Embeds the entire document.
    • Option 2: <object>: Older, similar to iframe but less common for general embeds, suitable for PDFs or legacy media.
    • Option 3: <embed>: Similar to <object>, generally for plugins.
    • Option 4: Direct link <a>: User downloads or opens in a new tab.
    • Considerations: <iframe> is most flexible for HTML/PDFs. For PDFs, consider offering a download link as an alternative for mobile users or those without plugin support. Performance can be an issue if embedding large files. Accessibility with embedded documents can be challenging. For simple static HTML, you might fetch content via AJAX and inject it, rather than an iframe, to maintain styling and control.

30. Describe the main components of a Web Component and how they foster encapsulation and reusability.

Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags. Their main components are:

  1. Custom Elements: Define your own HTML tags (e.g., <my-button>). You create a JavaScript class that extends HTMLElement and then register it with customElements.define(). This provides a custom API for your component.
  2. Shadow DOM: Provides encapsulation by attaching a separate, isolated DOM tree to an element. This "shadow tree" keeps the component's internal HTML structure, CSS styles, and behavior private from the main document. Styles inside the Shadow DOM don't leak out, and external styles don't leak in, ensuring consistent rendering.
  3. HTML Templates (<template> and <slot>):
    • The <template> element holds inert, client-side content that is not rendered until activated via JavaScript. This is the ideal place to define the component's internal structure.
    • The <slot> element is used within a Shadow DOM to create placeholders for content passed into the custom element from the outside. This enables flexible content distribution and composition.

Together, these foster encapsulation by isolating the component's internals (styles, markup, behavior) and reusability by providing a standardized way to define, register, and use components across different projects, much like native HTML elements.

Quick revision table

TopicOne-line answerCommon follow-up
HTML5 CoreModern HTML for multimedia, APIs, and semantics.What new tags did HTML5 introduce?
Semantic HTMLUsing tags that convey meaning (e.g., <article>).Why is <div> considered non-semantic?
Block vs. InlineBlock: new line, full width. Inline: same line, content width.How can CSS change an element's display type?
data-* AttributesCustom attributes for storing private data on elements.How do you access data-* attributes in JavaScript?
<img> vs. background-image<img> for content, background-image for decoration.How does alt attribute affect <img> accessibility?
defer vs. asyncasync: immediate, unordered. defer: after HTML, ordered.What happens if neither defer nor async is used?
ARIA AttributesProvide semantic info for accessibility tools.Give an example of an ARIA attribute and its use.
localStoragePersistent, origin-scoped, string-only client storage.What are the security concerns with localStorage?
Web WorkersRun JS in background threads for heavy tasks.What limitations do Web Workers have?
Web ComponentsCustom, reusable HTML elements with encapsulation.Name the three core technologies behind Web Components.
<picture> elementProvides responsive image solutions with multiple sources.How does srcset compare to <picture>?
Lazy LoadingDefers loading off-screen images/iframes (loading="lazy").What are the benefits of lazy loading?
Shadow DOMEncapsulates a component's internal structure and styles.How does Shadow DOM prevent CSS leaks?
Virtual DOMIn-memory representation for efficient DOM updates.Which JavaScript frameworks use Virtual DOM?
SSE vs. WebSocketsSSE: Server-to-client, one-way. WebSockets: Bidirectional, full-duplex.When is SSE preferable for real-time updates?

How to prepare

  • Understand Core Concepts: Solidify your grasp on fundamental HTML structure, semantic elements, and accessibility best practices. These are critical for every web developer.
  • Practice with Modern HTML5 APIs: Get hands-on with <audio>, <video>, <form> input types, Web Storage, and especially Web Components. Understand their use cases and limitations.
  • Focus on Performance & Accessibility: These are non-negotiable for modern web applications. Learn about responsive images, lazy loading, async/defer scripts, and ARIA attributes.
  • Build Small Projects: Apply your knowledge by building simple web pages or UI components. This reinforces concepts and helps you articulate design decisions.
  • Stay Updated: The web platform evolves. Keep an eye on new HTML standards, browser features, and best practices. "2026 Edition" implies knowing current recommendations.