HTML interview questions should reveal whether a candidate can build a document that communicates meaning, accepts input correctly, and remains usable across different ways of browsing. Knowing tag names is only the starting point. Recruiters need evidence that the candidate understands native controls, labels, document structure, parser behavior, resource loading, and the boundary between markup and application logic.
This guide to 100+ HTML Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It starts with document structure and everyday elements, then develops accessible forms, responsive media, interactive components, and production diagnosis. Use the practical examples to test reasoning about the page a browser actually constructs, rather than syntax recall alone.
How can recruiters assess genuine HTML and accessibility skills when interview assistance can hide gaps in a candidate’s explanation?
Ask the candidate to repair a mislabeled field, explain a missing form value, or predict how invalid nesting changes the DOM. Then ask how they would verify the repair with a keyboard and a browser inspector.
Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation, and unauthorized assistance during interviews.
Evaluate those signals alongside practical work and the candidate’s reasoning, rather than treating them as conclusive proof of misconduct. Fair HTML exercises should let candidates demonstrate diagnosis, semantic choices, and testing decisions under clear assumptions.
HTML Interview Questions
The complete question bank appears first so interviewers can choose prompts without revealing the answers. State the supported browsers and any framework assumptions before asking candidates to reason about edge cases.
HTML Interview Questions for Beginners
Test the document model, meaningful elements, links, images, tables, and basic form behavior. Ask candidates to explain why their markup is appropriate, not simply whether it looks correct.
What is HTML, and what does it contribute to a web page?
How do HTML, CSS, and JavaScript work together?
What does the HTML doctype do?
What belongs in a minimal HTML document?
How do an element, a tag, and an attribute differ?
Which HTML elements are void elements?
Why does correct nesting matter if browsers repair malformed HTML?
How do you display reserved characters as text in HTML?
Why should a page declare its character encoding early?
What do lang and dir communicate?
What is semantic HTML?
How should heading levels be chosen?
When should you use p, br, and hr?
How do strong and em differ from b and i?
What is the difference between div and span?
How do id and class differ?
What is the difference between an absolute and a relative URL?
When should you use a link instead of a button?
What makes link text useful?
How do you choose an image's alt text?
Why should images have width and height attributes?
How do ul, ol, and dl represent different relationships?
When should content be represented as a table?
How do th, td, and caption improve a data table?
What does a form element do?
Why are name and id both useful on form controls?
How do you associate a label with an input?
How do input types affect behavior?
How do radio buttons differ from checkboxes?
When should you use select rather than a text input?
How is textarea different from input?
Why should a button's type be explicit?
How do GET and POST form submissions differ?
What does the required attribute provide?
How do disabled and readonly differ?
What belongs in the head rather than the body?
How do title and meta description differ?
How do you connect a stylesheet and a script to HTML?
What does the viewport meta declaration do?
How would you check a basic HTML page before handing it over?
HTML Interview Questions for Intermediate
Explore relationships between structure, accessible names, submission rules, resource loading, and native interaction. Use small examples that make hidden assumptions visible.
How do section, article, and aside differ?
How should main, nav, header, and footer be used?
What is an accessible name, and how does it differ from a description?
When should you use aria-label or aria-labelledby?
Why is placeholder text not a replacement for a label?
How do fieldset and legend help with related controls?
Which controls contribute entries to a form submission?
How do boolean attributes differ from string-valued settings?
How do autocomplete and inputmode serve different purposes?
How do min, max, step, and pattern participate in validation?
How should native and custom validation be combined?
What is the difference between submitting a form and calling form.submit()?
What is required for an ordinary file-upload form?
How do HTML attributes and DOM properties differ?
When should data-* attributes be used?
How do hidden, aria-hidden, and inert differ?
How should tabindex values be chosen?
What makes a skip link useful?
How do details and summary provide a disclosure control?
How is a modal dialog different from a dialog displayed with open?
What does the HTML popover mechanism provide?
How do srcset and sizes help with responsive images?
When should picture be used instead of only srcset on img?
When is native lazy loading appropriate for images?
How should audio and video content be made usable?
What should an iframe include beyond its src URL?
How do async, defer, and module scripts differ?
What is the relationship between DOMContentLoaded and load?
How does template differ from an ordinary hidden container?
What do slots contribute to a web component?
Why should HTML components avoid duplicate IDs?
How do you make a complex table's header relationships clear?
What happens when an HTML anchor opens a new tab?
How should canonical links and metadata be used responsibly?
How does progressive enhancement influence form design?
How can content order differ from visual order, and why does it matter?
How should focus be handled after a dynamic content change?
How do HTML fragments and full documents parse differently?
What should you check when a native control looks different across browsers?
How can a conformance checker help without replacing manual testing?
HTML Interview Questions for Experienced
Use these scenarios to assess diagnosis, security boundaries, component design, interoperability, and regression testing. Strong candidates separate what HTML provides from responsibilities belonging to scripts, servers, and product design.
How would you diagnose a page whose DOM differs from its HTML source?
Why can invalid table markup produce surprising node placement?
How can HTML parsing cause a hydration mismatch?
How would you review HTML generated by a CMS or rich-text editor?
What makes HTML injection different from safely displaying text?
Why is removing script tags not enough to sanitize HTML?
What role can Content Security Policy play for HTML pages?
How do Trusted Types help with DOM injection risks?
How would you embed untrusted content with an iframe?
How do you prevent a form's HTML from creating a false sense of security?
How would you investigate a field that is visible but missing from submitted data?
How would you design accessible validation for a long form?
What should a custom combobox implementation account for?
How would you decide between a native dialog and a custom overlay?
How would you assess accessibility beyond automated checks?
How can overly aggressive ARIA make an HTML interface worse?
How would you design an icon-only action button?
How do you manage dynamic status messages without disrupting focus?
How would you make a responsive image strategy measurable?
What can HTML contribute to improving initial rendering performance?
How should preload be used without wasting bandwidth?
How would you evaluate a new HTML feature before adopting it?
What is progressive enhancement's relationship to feature detection?
How would you handle multilingual and bidirectional user content?
What should a reusable HTML form component guarantee?
How would you test a component using shadow DOM?
How can native form participation be added to a custom element?
How would you prevent duplicate submissions without breaking forms?
Why does a valid DOM not necessarily mean safe or correct content?
How would you review third-party HTML embeds before integration?
How would you investigate a link that behaves incorrectly only after deployment?
How should forms handle server-side errors after a navigation?
How would you design HTML for printing or nonvisual consumption?
What should an HTML-focused performance audit avoid confusing?
How would you build regression tests for HTML semantics?
How would you migrate old presentational markup to modern HTML?
How would you debug a page that works with a mouse but fails with a keyboard?
How would you evaluate an HTML answer that relies on outdated browser myths?
How would you design a practical senior HTML interview exercise?
What does a strong production HTML review cover?
HTML Interview Questions and Answers
The answers reproduce the question bank’s exact wording and numbering. They use HTML Living Standard terminology and distinguish markup from CSS, JavaScript, and server responsibilities. Code blocks are HTML documents or labeled fragments; scripts inside a fragment are included only where they explain the interaction. Named assets and endpoints are illustrative unless supplied. Examples received static review, with separate targeted native-behavior checks in one Chrome environment; this is not execution of every example or cross-browser and screen-reader certification. Check current support for the specific newer features used by your application.
HTML Interview Questions and Answers for Beginners
These answers establish a reliable foundation for writing and reviewing ordinary pages. The examples emphasize native behavior and clear content relationships.
1. What is HTML, and what does it contribute to a web page?
HTML is the markup language used to describe a document's content and meaning. It identifies headings, paragraphs, links, forms, images, and other structures that browsers can render and expose to assistive technologies. It is not a general-purpose programming language. A useful interview answer separates this document structure from CSS presentation and JavaScript behavior. I would start with meaningful native elements so the page remains understandable when styling changes, scripts fail, or a user navigates through something other than the visual layout.
2. How do HTML, CSS, and JavaScript work together?
HTML expresses content and semantics, CSS controls presentation, and JavaScript can add behavior or modify the document. These responsibilities interact but should not be confused. A native button already has useful keyboard and form behavior before JavaScript is attached, while styling a div to look like a button does not give it the same semantics. I would implement the simplest functional HTML first, then add styling and enhancements without making essential information depend unnecessarily on a successful script download.
3. What does the HTML doctype do?
The standard <!doctype html> declaration helps a browser use standards mode rather than legacy quirks behavior. It is not an HTML element, does not download a schema, and does not select a numbered HTML library version. I would place it at the beginning of an HTML document and inspect document.compatMode when diagnosing an unexpected rendering mode. A page can look acceptable in quirks mode while still having layout differences, so visual appearance alone is not evidence that the document has the intended mode.
4. What belongs in a minimal HTML document?
A useful minimal document declares the doctype, document language, character encoding, a meaningful title, and a body containing the page's content. A responsive page normally also includes an appropriate viewport declaration. Some tags can legally be omitted under specific HTML syntax rules, but explicit structure is clearer for learning and maintenance. I would distinguish an intentionally small valid document from an incomplete application: metadata, form handling, accessible content, and resource delivery still need attention as the page grows.
Expected behavior: A standards-mode document with an English language declaration, a title, and a main heading.
5. How do an element, a tag, and an attribute differ?
An element is a structural part of the document, a tag is markup used to represent it, and an attribute supplies additional information or configuration. For example, an anchor element can have an href attribute identifying its destination. The parsed DOM is not simply a collection of literal source tags, because the parser can create or rearrange nodes under its rules. I would use these terms precisely when explaining a bug: a missing end tag, an incorrect attribute value, and a wrong DOM relationship are different problems.
6. Which HTML elements are void elements?
Void elements, such as img, input, br, meta, and link, do not have child content or an end tag in HTML syntax. An XML-style trailing slash does not make an ordinary HTML element self-closing. For example, writing a slash on a div start tag does not replace its required closing structure. I would avoid presenting XHTML syntax rules as universal HTML rules and check whether a document is actually served as HTML or XML before predicting how the browser will parse it.
7. Why does correct nesting matter if browsers repair malformed HTML?
Browsers use defined parsing rules to recover from many markup errors, but the repaired DOM may differ from the author's intended structure. A paragraph cannot contain every kind of block structure, and a table has specialized parsing rules. Incorrect nesting can therefore change styling selectors, accessibility relationships, or JavaScript behavior. I would inspect the live DOM as well as the source and fix the markup, rather than depend on a recovery result merely because one browser appears to display the page acceptably.
8. How do you display reserved characters as text in HTML?
Use character references when a character could otherwise be interpreted as markup or an attribute delimiter. For example, < displays a less-than sign, and & displays an ampersand. The appropriate escaping depends on whether the value is in text, an attribute, a URL, or a script context. I would not describe replacing angle brackets as a complete security strategy. For ordinary text inserted with JavaScript, textContent avoids parsing the value as HTML and often expresses the intended operation directly.
Expected behavior: The first paragraph displays literal <h1> text; the second displays an ampersand.
9. Why should a page declare its character encoding early?
A consistent encoding lets the browser interpret bytes as the intended characters. A UTF-8 meta declaration belongs early in the document, within the standard's prescribed initial byte range, and the server's Content-Type configuration should agree. Encoding mistakes can corrupt names, punctuation, and multilingual content even when the HTML structure is otherwise sound. I would inspect response headers and actual file encoding together, because adding a meta tag cannot reliably compensate for every contradictory transport-level declaration or incorrectly encoded source file.
Expected behavior: Names retain their accented characters when the file and HTTP encoding are consistent with UTF-8.
10. What do lang and dir communicate?
The lang attribute identifies the language of content, while dir describes text direction, such as ltr, rtl, or auto. They solve different problems and can be applied to a subtree when content changes language or direction. Language information can influence pronunciation and other user-agent behavior; direction is important for mixed-script content and layout. I would not infer language solely from a country's name or use CSS alignment as a substitute for correct directionality. User-generated names often need careful bidirectional-text handling.
Expected behavior: The Arabic span has its own language and direction; surrounding English retains the document context.
11. What is semantic HTML?
Semantic HTML uses elements according to the meaning of the content, not just their default appearance. A heading identifies a heading, a button performs an action, and a navigation region groups navigation links. This helps browsers, assistive technologies, and maintainers interpret the page consistently. It does not automatically guarantee accessibility or search visibility. I would inspect whether the chosen element matches the interaction and content relationship, then verify names, keyboard behavior, and visual presentation rather than stopping at the presence of modern-looking tags.
12. How should heading levels be chosen?
Choose heading levels to describe the content hierarchy, with the page's main heading and logically nested subsections. Do not select a heading level merely for its default font size; CSS handles appearance. I would normally give a page one clear primary heading and use lower levels for subordinate topics. Sectioning elements do not make every nested h1 behave as a reliably understood automatic outline. Test the exposed heading structure and keep it consistent with the visible organization and the user's navigation needs.
13. When should you use p, br, and hr?
A p element represents a paragraph, br introduces a line break within content where that break is meaningful, and hr represents a thematic break. They are not interchangeable spacing tools. For example, line breaks may be suitable in an address or poem, while separate prose paragraphs should use separate p elements. I would use CSS for visual margins rather than repeated br tags. Choosing the right structure makes content easier to restyle and prevents visual spacing tricks from replacing relationships that users need to understand.
14. How do strong and em differ from b and i?
Strong marks importance, seriousness, or urgency, while em marks stress emphasis that can affect meaning. The b and i elements have other text-level uses, such as drawing attention without extra importance or marking an alternate voice or term. None should be chosen solely to request bold or italic styling. I would identify what the text means and use CSS when the requirement is purely visual. Also avoid promising a particular screen-reader vocal effect, since presentation of these distinctions varies by technology and settings.
15. What is the difference between div and span?
Div and span are generic containers used when no more meaningful element fits. Div generally groups flow content, while span groups phrasing content within text. Their familiar block and inline appearances are default styling behaviors, not a substitute for understanding their content models. I would not replace a button, heading, or list with a generic container simply because it is easier to style. Generic wrappers are useful for layout and scripting, but they should preserve the meaningful structure of the content inside them.
16. How do id and class differ?
An id identifies one element within its tree and can be used by fragment links, labels, scripts, and accessibility references. A class groups elements for styling or other application conventions and can appear on many elements. Duplicate IDs can make relationships ambiguous even if a selector appears to work. I would generate stable unique identifiers for repeated components and use classes for shared presentation. Neither attribute is a security boundary, and hiding or renaming an element does not protect information already delivered to the browser.
17. What is the difference between an absolute and a relative URL?
An absolute URL identifies a resource with a complete scheme and location, while a relative URL is resolved against a base URL. A path beginning with a slash is relative to the origin's root, while another path can be relative to the current document location. I would test links under the actual deployment path instead of assuming the application always lives at the site root. A base element can change resolution across the document, so it deserves explicit review when relative links behave unexpectedly.
18. When should you use a link instead of a button?
Use an anchor with href to navigate to a destination and a button to perform an action such as opening a dialog or submitting a form. Native elements provide different keyboard behavior and browser affordances, including opening links in another tab. Styling one to resemble the other does not change its underlying purpose. I would avoid href="#" as a generic action placeholder and avoid a clickable div where a native control fits. The element should match what activation actually does for the user.
The account destination is illustrative; the local help interaction is self-contained.
Expected behavior: The anchor navigates to an account page; the button reveals help without submitting a form.
19. What makes link text useful?
Useful link text identifies the destination or purpose clearly in context. Repeated labels such as 'click here' can be difficult to distinguish, especially when users navigate a list of links. I would make the visible wording descriptive and keep any additional accessible naming consistent with it. A link's title attribute is not a dependable substitute for meaningful text. If an image is the only content of a link, its text alternative needs to convey the link's purpose rather than merely describe decorative details.
20. How do you choose an image's alt text?
Choose alt text according to the image's purpose in its context. An informative image needs an equivalent concise description; a purely decorative image generally uses alt="" so it can be ignored. A functional image needs an alternative describing the action or destination. Omitting alt is not the same as providing an empty alternative. I would avoid repeating nearby text unnecessarily and provide a longer explanation elsewhere for complex information that cannot be expressed usefully in a short attribute.
The named image assets must be supplied to display the pictures.
Expected behavior: The informative image has contextual alternative text; the decorative image has an empty alternative.
21. Why should images have width and height attributes?
Appropriate width and height attributes communicate intrinsic dimensions and help the browser reserve space before an image loads, reducing layout movement. CSS can still make the displayed image responsive, commonly with a constrained width and proportional height. The declared ratio should match the intended image dimensions rather than arbitrary layout guesses. I would also inspect the actual resource and responsive variants, because reserving the wrong ratio can still lead to shifting or distortion. Dimensions do not replace meaningful alt text or efficient image delivery.
22. How do ul, ol, and dl represent different relationships?
Ul represents a list where ordering is not central, ol represents an ordered list, and dl groups names or terms with descriptions. Their choice should reflect the content relationship rather than a preferred marker style. A recipe's steps may need an ol, while navigation links may form a ul. I would not use a list solely to indent unrelated paragraphs or use manual numbers when the content is genuinely an ordered list. Correct markup preserves relationships when styles are unavailable or content is reorganized.
23. When should content be represented as a table?
Use a table for data whose meaning depends on relationships between rows and columns. Use CSS layout techniques for arranging a page visually. A data table should have meaningful headers and, when helpful, a caption describing its subject. I would ask what a user needs to compare before choosing a table, especially on narrow screens. Converting real tabular data into unrelated visual cards can lose important relationships, while using tables for page layout creates misleading structure and unnecessary navigation complexity.
Expected behavior: Each session is a row header and each numeric cell belongs to the Seats remaining column.
24. How do th, td, and caption improve a data table?
Th identifies a header cell, td identifies a data cell, and caption provides a table-level description. In a straightforward table, scope="col" or scope="row" can clarify which cells a header applies to. Complex relationships may require more explicit associations or, preferably, a simpler design. I would verify how headers are announced while navigating the table rather than rely on bold styling alone. A visually prominent first row made entirely of td cells does not convey the same header semantics.
25. What does a form element do?
A form groups controls for collecting and submitting information. Its action, method, and encoding help define how the browser sends an entry list to a destination. Native form behavior provides a useful foundation before JavaScript enhancement, but a server still has to process and validate the submission. I would ensure the form has clear labels, meaningful control names, and an intentional submit button. A collection of inputs outside a form is not automatically equivalent, although controls can explicitly associate with a form by ID.
26. Why are name and id both useful on form controls?
The name identifies a control's contribution to submitted form data, while id lets other elements or scripts reference that specific control. A label's for attribute normally points to the id, not the name. Controls can share a name when the data model calls for repeated values or a radio group, but IDs should remain unique. I would inspect the constructed form data when a field seems missing, because a visible, labeled input without a submission name may not contribute the expected entry.
27. How do you associate a label with an input?
A visible label can explicitly reference a labelable control using for and a matching unique id, or wrap the control where that structure is appropriate. This supplies a meaningful name and often expands the activation area. I would prefer clear visible labels over relying only on placeholder text or an icon. Additional help can be linked separately as a description. Testing should include clicking the label, keyboard navigation, and inspecting the accessible name, because visual proximity alone does not establish a programmatic association.
The /subscribe endpoint must be implemented and validate the request; this fragment is not a complete backend.
Expected behavior: The label names the email control; help text supplies its description; ordinary invalid submission is blocked.
28. How do input types affect behavior?
Input types tell the browser what kind of control and value behavior is intended. Email, number, date, checkbox, and file inputs have different interaction and validation rules. Their presentation varies across browsers and devices, so I would not depend on an identical picker or keyboard everywhere. Select a type according to the data's meaning: a postal code or account identifier is not necessarily a number for arithmetic. Server validation remains necessary, and inputmode can offer a keyboard hint without redefining the underlying data type.
29. How do radio buttons differ from checkboxes?
Radio buttons with the same name and appropriate form relationship represent a mutually exclusive choice, while checkboxes usually represent independent on/off selections. Each needs a clear label, and related controls benefit from a fieldset and legend explaining the group. I would provide distinct values for the server to interpret and test keyboard interaction. A checkbox that is not checked normally contributes no entry during standard submission, so the backend should not assume every rendered option will arrive with an explicit false value.
Expected behavior: The choices share a group name and legend; selecting one radio deselects the other.
30. When should you use select rather than a text input?
Use select when users must choose from a manageable, known set of options and free text is not appropriate. A text input is better when the allowed values are open-ended or the list would be unwieldy. Native selects provide useful platform behavior but have presentation differences, so replacing them with a custom widget introduces substantial keyboard and accessibility work. I would choose according to the task, label the control clearly, and ensure the submitted option values match the application's data contract.
31. How is textarea different from input?
Textarea provides a multiline text-editing control, while most text-like input types are single-line. In HTML markup, a textarea's initial value is its text content rather than a value attribute. Rows and cols can suggest an initial size, while CSS controls layout. I would provide a persistent label and appropriate instructions, and avoid assuming multiline text is safe to insert back into HTML without escaping. Its content is user data; the application must define length limits, validation, and safe rendering separately.
Expected behavior: The textarea starts with the text between its tags, and the label identifies the control.
32. Why should a button's type be explicit?
A button associated with a form can submit it when its type is omitted in common contexts, which can surprise an interface using buttons for secondary actions. Setting type="button" for an ordinary scripted action and type="submit" for submission makes the intent clear. I would also consider whether a reset button is genuinely useful, since it can discard entered values unexpectedly. The label should describe the action, and disabled or loading behavior should not leave users unsure whether their request has been accepted.
33. How do GET and POST form submissions differ?
GET encodes form data into the request URL and is suitable for retrieval actions such as a search that can be bookmarked. POST sends data in the request body and is commonly used for state-changing operations. POST is not encryption and does not by itself prevent forgery or unauthorized actions. I would use HTTPS and appropriate server controls, avoid exposing sensitive data in URLs, and select the method based on the operation's semantics rather than assuming one method automatically makes a form secure.
34. What does the required attribute provide?
Required participates in native constraint validation for supported controls, helping prevent an ordinary submission when an expected value is missing. Its exact behavior depends on the control type, such as checkbox or radio-group rules. It does not establish business authorization or guarantee that a request reaching the server contains valid data. I would explain requirements visibly, test the native error experience, and validate again on the server. Adding an asterisk without a programmatic requirement does not provide the same behavior.
35. How do disabled and readonly differ?
Disabled controls are generally unavailable for interaction and excluded from standard form submission, while readonly applies only to certain controls and allows their values to be submitted while preventing ordinary editing. Readonly does not apply to every input-like element, such as select. I would choose based on the interaction and data contract, then test focus and submission behavior. Neither is a trust boundary: a client can construct a different request, so the server must not trust a value merely because the page displayed it as uneditable.
No submit control is included; inspect the form’s entry list rather than treating this fragment as a complete workflow.
Expected behavior: Native form data includes reference=ref-42 and excludes the disabled control.
36. What belongs in the head rather than the body?
The head contains document metadata and resources such as the title, encoding declaration, stylesheet links, and other supported metadata. The body contains the document's main content. Scripts can appear in different permitted locations, with loading behavior depending on their attributes and type. I would not use head as a hidden container for ordinary page text. Browsers may repair misplaced markup, but relying on repair can create unexpected structure and does not make the source conforming or maintainable.
37. How do title and meta description differ?
The title names the document and is used in browser interfaces such as tabs and bookmarks. A meta description summarizes the page for consumers that choose to use it. Neither should be a list of unrelated keywords. I would make both specific to the page and align the title with its visible purpose. A search engine may generate a different snippet, so a meta description is not a guarantee of displayed text or ranking, and the document title is not a replacement for an on-page heading.
38. How do you connect a stylesheet and a script to HTML?
A stylesheet is commonly linked with a link element using rel="stylesheet", while a script element can load JavaScript through src. Their placement and attributes affect discovery and execution behavior. For a parser-inserted classic external script, defer is often useful when the script needs the parsed document. I would avoid claiming that all scripts block parsing identically, because modules and async scripts have different rules. Resource URLs, response types, and failed loads should be checked when a correctly written tag appears ineffective.
39. What does the viewport meta declaration do?
A viewport declaration such as width=device-width, initial-scale=1 helps mobile browsers use a layout viewport appropriate to the device rather than a wider legacy default. It does not itself make layouts responsive; CSS and suitable content sizing still matter. I would preserve the user's ability to zoom rather than add restrictive scaling settings. Test long text, narrow widths, and larger font settings, because a viewport tag cannot compensate for fixed-width content or controls that overflow their container.
40. How would you check a basic HTML page before handing it over?
I would inspect the parsed structure, confirm that links and form controls have meaningful names, and test keyboard navigation and ordinary submission behavior. Then check the page at different widths, with missing resources, and with scripts disabled where the core task should still work. A conformance checker can catch markup mistakes but cannot prove usability or accessibility by itself. I would combine automated checks with focused manual scenarios and record what was actually tested rather than treat a visually correct screenshot as complete validation.
HTML Interview Questions and Answers for Intermediate
These answers connect markup to actual browser and accessibility behavior. Verify the relevant state and context before proposing a broad workaround.
41. How do section, article, and aside differ?
Section groups a thematic part of a document, article represents a self-contained composition that can make sense independently, and aside contains tangentially related content. None is a universal replacement for div. I would ask whether the group has a meaningful topic and heading, whether it can stand alone, and how it relates to surrounding material. An accessible name can also affect whether certain elements are exposed as landmarks, so I would inspect the accessibility tree rather than infer navigation behavior solely from the tag name.
42. How should main, nav, header, and footer be used?
Main identifies the document's dominant content, nav marks a significant navigation section, and header and footer provide introductory or closing information for their context. Their landmark exposure depends partly on nesting and context; an article's header is not necessarily the page-wide banner. I would provide a clear main region and distinguish multiple navigation areas with useful labels. Not every collection of links needs a nav element, and adding many redundant landmarks can make navigation noisier rather than easier.
Expected behavior: The document has page-level header/footer, a named navigation region, and a main content region.
43. What is an accessible name, and how does it differ from a description?
An accessible name identifies an element, such as a button's action or an input's label. A description supplies additional guidance, constraints, or context without replacing that identity. Native text and label relationships often provide the best starting point. I would inspect the computed name and description when debugging rather than assume every visible string is included. Competing naming attributes can override visible text, creating confusion for screen-reader and voice-control users if the exposed name no longer matches what they see.
44. When should you use aria-label or aria-labelledby?
Use them when a supported element needs an accessible name that native HTML relationships do not adequately provide. Aria-labelledby can reference existing visible text, while aria-label supplies a string. Prefer a visible native label for ordinary form fields rather than using ARIA to hide a missing design requirement. I would avoid redundant or conflicting names and verify that the references point to the intended unique elements. These attributes add naming information; they do not supply missing keyboard behavior or turn an arbitrary element into a complete control.
45. Why is placeholder text not a replacement for a label?
A placeholder is a hint shown within an empty control and commonly disappears when the user enters a value. That makes it unreliable as the persistent identification of the field. It may also have insufficient contrast or be mistaken for prefilled data. I would provide a visible label and use separate instructions for formats or constraints. Even if a technology exposes a placeholder in some circumstances, that fallback does not solve the usability problem of losing the field's identity while reviewing entered information.
46. How do fieldset and legend help with related controls?
Fieldset groups related controls, and legend names that group. They are especially useful for radio buttons or checkboxes whose individual labels do not explain the shared question. For example, 'Email' and 'Phone' need context if they are choices for preferred contact method. I would keep the legend concise and use individual labels for each control. Grouping should match the task rather than surround every field indiscriminately, and complex forms still need logical ordering, instructions, and usable validation feedback.
47. Which controls contribute entries to a form submission?
Submission builds an entry list from eligible controls associated with the form. Names, disabled state, checked state, selected options, and the activated submitter all matter. An unchecked checkbox usually contributes no entry, while multiple selected options can contribute repeated names. I would inspect FormData or the request payload using representative states rather than assume every visible input is sent. Readonly controls can contribute values, and controls outside the form can participate through an explicit form association, so DOM containment alone is not the whole rule.
This demonstration prevents navigation and only displays the locally constructed data. The FormData submitter overload requires supporting browsers.
Expected behavior: Activating Save with Updates unchecked reports displayName and intent entries, without an updates entry.
48. How do boolean attributes differ from string-valued settings?
For a boolean attribute, presence means true and absence means false. Writing disabled="false" still disables the control because the attribute is present. This differs from enumerated attributes whose values select defined states, such as contenteditable or spellcheck. I would use DOM properties or appropriate attribute removal to change boolean state and verify the attribute's actual category before applying a generic serializer. Treating every HTML attribute as a free-form Boolean string is a common source of framework and template bugs.
Expected behavior: The first control is disabled because the attribute is present; the second is enabled.
49. How do autocomplete and inputmode serve different purposes?
Autocomplete describes the meaning of a field or preferred autofill behavior using defined tokens, while inputmode suggests an appropriate input mechanism such as a numeric keyboard. Neither replaces the control's type, name, label, or server-side validation. A payment-card number, for example, is an identifier rather than a quantity for arithmetic. I would choose tokens according to the real data and test representative password managers and mobile keyboards, recognizing that user agents can make their own decisions about autofill and input presentation.
No numeric-only restriction is added because postal formats depend on the supported country or region.
Expected behavior: The value remains text and carries a postal-code autofill hint.
50. How do min, max, step, and pattern participate in validation?
These attributes express different constraints for the input types to which they apply. Min and max can bound numeric or date-like values, step defines permitted increments, and pattern constrains supported text input values with a regular expression. They are not interchangeable or universally applicable. I would provide understandable instructions and test empty, boundary, and malformed values, including interactions with required. The server must enforce the same business rules, because browser constraints can be bypassed and do not cover every domain requirement.
51. How should native and custom validation be combined?
Use native constraints where they express the requirement, then add custom validation for rules the built-in model cannot represent. The constraint-validation APIs can report state and set a custom validity message, which must be cleared when the value becomes valid. I would preserve meaningful focus, visible error text, and programmatic relationships to affected fields. A red border alone is insufficient. Also validate on the server and return recoverable errors, since passing browser validation says nothing about authorization or changes that occurred after the page loaded.
52. What is the difference between submitting a form and calling form.submit()?
The submit() method directly submits without the usual interactive constraint-validation and submit-event path. requestSubmit() behaves more like activating a submit button, including validation and an appropriate submit event, and can accept a submitter. I would choose based on whether normal user-facing submission behavior should run. A control named submit can also shadow the method on a form, making careless calls fail. Tests should cover the actual entry point, because intercepting a click is not equivalent to handling every way a form can be submitted.
53. What is required for an ordinary file-upload form?
A file input provides the selection control, and a POST form commonly uses multipart/form-data to send file content. The accept attribute can guide selection but is not proof that an uploaded file is safe or of the claimed type. I would label the control, state size and format expectations, and validate uploads on the server with appropriate storage and access policies. A browser should not be expected to reveal an arbitrary local filesystem path or let a page silently choose files on the user's behalf.
54. How do HTML attributes and DOM properties differ?
Attributes represent markup-level configuration, while DOM properties expose runtime state and APIs. Some properties reflect attributes closely, but others diverge as a user interacts. An input's value attribute describes its default value, while its value property can hold the current edited value. I would inspect the correct layer when a script appears to read stale data. Framework bindings need similar care: serializing attributes, reading live properties, and resetting a form can have different consequences even when the names look identical.
55. When should data-* attributes be used?
Data attributes attach application-specific string data to elements without inventing unrelated HTML attributes. JavaScript can access them through dataset, with name conversion rules between hyphenated attributes and property names. They are useful for modest behavior hooks or identifiers, but not a place to store secrets or large application state unnecessarily. I would parse values explicitly because the values are strings and preserve semantic attributes for their real purpose. A data attribute alone does not create accessible meaning or enforce a security policy.
56. How do hidden, aria-hidden, and inert differ?
Hidden indicates content that is not currently relevant for rendering, with special behavior for the until-found state. Aria-hidden affects exposure to accessibility APIs without itself removing visual presentation or keyboard focus. Inert disables user interaction and focus within the subtree and affects its accessibility exposure. I would not place focusable controls under aria-hidden and assume they are safely disabled. Choose the mechanism according to visibility, interaction, and accessibility requirements, then test actual browser and assistive-technology behavior rather than treating these attributes as synonyms.
57. How should tabindex values be chosen?
Tabindex="0" places an otherwise suitable element in sequential focus order, while a negative value commonly allows programmatic focus without including it in ordinary tab navigation. Positive values create a separate ordering that is difficult to maintain and usually should be avoided. I would prefer native focusable controls and a logical DOM order. Adding tabindex does not provide a role, keyboard activation behavior, or an accessible name, so it cannot by itself repair a generic element being used as a custom button.
58. What makes a skip link useful?
A skip link lets keyboard users move past repeated content to the main part of the page. It should target a real meaningful destination, be available early in navigation, and become visible when focused if normally visually concealed. I would verify both scroll and focus behavior in the target browsers rather than check only that the URL fragment changes. A clear main region and sensible document order complement the link; the link does not compensate for a page with otherwise confusing structure or trapped focus.
Verify fragment focus and scrolling in the supported browsers.
Expected behavior: The skip link targets the main region, which can receive focus without becoming an ordinary additional tab stop.
59. How do details and summary provide a disclosure control?
Details represents a disclosure section, and its summary supplies the visible label used to expand or collapse it. This gives a useful native starting point without scripting a custom accordion from generic elements. I would keep the summary understandable and avoid conflicting interactive content inside its activation area. The open attribute controls the expanded state, but the default presentation and accessibility behavior should still be tested. A collection of disclosures is not automatically a tab interface or a modal dialog.
Expected behavior: Activating the summary opens or closes the disclosure without custom JavaScript.
60. How is a modal dialog different from a dialog displayed with open?
A dialog shown with showModal() enters the modal interaction model and makes the surrounding document inert, while a dialog with the open attribute is not automatically modal. The element still needs an accessible name, sensible initial focus, a closing mechanism, and appropriate focus restoration. I would use the native API where it fits and test keyboard and assistive-technology behavior. Simply styling an element above the page or adding aria-modal does not implement all the interaction rules of a real modal workflow.
Test focus, Escape behavior, and restoration in the target environment. This is a small interaction example, not a complete registration workflow.
Expected behavior: The opener shows a named modal dialog; its Close button closes it through a dialog form.
61. What does the HTML popover mechanism provide?
The popover attribute and related invoker attributes provide built-in showing, hiding, and top-layer behavior for suitable nonmodal content. Auto popovers also have dismissal behavior, but the mechanism does not automatically choose the correct semantic role or make the rest of the page inert. I would distinguish a popover from a modal dialog and verify current support for the specific features used. If it contains an interactive widget, its labeling, focus expectations, and keyboard behavior still need a deliberate design.
The mechanism needs no JavaScript here; unsupported environments need a deliberate fallback if this help is essential.
Expected behavior: In supporting browsers, the button toggles a nonmodal auto popover that supports light dismissal.
62. How do srcset and sizes help with responsive images?
Srcset offers candidate image resources, and sizes describes the expected rendered slot width when using width descriptors. The browser combines that information with its environment to select a candidate; it is not an instruction to download one exact file in every situation. Density descriptors support a different selection model. I would ensure candidate dimensions and slot assumptions are accurate and test actual network choices at representative widths. CSS still controls layout, and alt text belongs on the img element regardless of the selected resource.
This assumes a full-viewport slot up to 600px and a 600px slot beyond that. Supply actual candidate files at the declared widths and matching aspect ratio; CSS must agree with the intended layout.
Expected behavior: The browser can select a candidate using the declared slot size and resource widths.
63. When should picture be used instead of only srcset on img?
Picture is useful for art direction or selecting alternatives by media conditions and supported formats, while srcset on img often suffices for different resolutions of the same composition. Picture contains source alternatives and an img fallback that also carries the text alternative. I would keep the alternatives semantically equivalent or adjust surrounding explanation when the visual information changes. An incorrect source order or media condition can select the wrong crop, so test actual viewport cases rather than assume the markup's appearance proves correct resource selection.
Supply both images with equivalent essential information. This example assumes both crops share the declared 3:2 aspect ratio.
Expected behavior: A narrow viewport selects the close-up candidate in supporting browsers; the img supplies fallback and alt text.
64. When is native lazy loading appropriate for images?
Loading="lazy" can defer fetching images that are not immediately needed, which can reduce initial resource work. It is usually inappropriate for an important image visible immediately, especially one central to initial rendering. I would reserve space with dimensions, inspect real loading behavior, and avoid treating lazy loading as a precise scheduling guarantee. Browser heuristics and script settings can influence it. The attribute does not compress a large image or solve slow delivery by itself; resource size and prioritization remain separate concerns.
65. How should audio and video content be made usable?
Provide suitable native controls or a thoroughly tested accessible player, along with the alternatives users need for the content. Captions, transcripts, and audio descriptions address different needs and are not interchangeable. Track can associate timed text such as captions with media, but valid markup alone does not establish that the captions are accurate or complete. I would avoid assuming autoplay will succeed and let users control playback. Test keyboard operation and the media alternatives as part of the real content experience.
66. What should an iframe include beyond its src URL?
An iframe needs a meaningful title identifying the embedded content, along with deliberate sizing and an assessment of permissions and trust. Sandbox, allow, referrerpolicy, and loading can be relevant, but each has a distinct purpose. I would avoid granting capabilities merely to silence an integration error. The embedded document has its own context and may fail, require authentication, or behave differently across devices. Provide an appropriate fallback route and test keyboard navigation between the surrounding page and the embedded content.
67. How do async, defer, and module scripts differ?
For parser-inserted classic external scripts, defer delays execution until parsing finishes and preserves their document order, while async permits execution when ready without that ordering guarantee. Module scripts are deferred by default unless their configuration changes the behavior, and their dependencies follow the module loading model. I would choose attributes according to dependencies rather than add both indiscriminately. Dynamically inserted scripts and inline scripts have different details, so describe the specific case instead of claiming every script with an attribute follows one universal timeline.
Supply both script resources. Do not infer a shared dependency contract between unrelated classic and module scripts from this example.
Expected behavior: The classic external script is deferred; the module follows module loading and default deferred execution behavior.
68. What is the relationship between DOMContentLoaded and load?
DOMContentLoaded signals that the document has been parsed and deferred scripts have run, without waiting for every resource such as images. Load waits for the document's dependent resources under its loading rules. Async scripts are not ordered before DOMContentLoaded merely because they appear earlier in markup. I would attach behavior at the earliest appropriate point and account for code that runs after an event has already fired. Waiting for load unnecessarily can delay interaction, while assuming an image is ready at DOMContentLoaded can also be wrong.
69. How does template differ from an ordinary hidden container?
A template stores a document fragment whose ordinary contents are not rendered as part of the surrounding page until inserted or otherwise used. It is intended for reusable markup, not merely styling an element invisible. Scripts can clone its content, but repeated IDs and unsafe data insertion still need attention. I would distinguish ordinary templates from declarative shadow-root syntax, which has different processing behavior. Being inside a template is not a security guarantee for content that will later be inserted into an active document.
Expected behavior: The template remains a source fragment, and one paragraph is inserted into the messages section.
70. What do slots contribute to a web component?
Slots define insertion points where a shadow tree can present assigned light-DOM content. They help a component expose a structured content contract while keeping its internal markup separate. Slotting does not copy the nodes into arbitrary new ownership or automatically solve accessible naming. I would document expected slot names and fallback content, then test interactions involving focus, labels, and the accessibility tree. Shadow DOM is a browser API used with HTML, not a universal guarantee that a custom element behaves like a native control.
71. Why should HTML components avoid duplicate IDs?
IDs support relationships such as label associations, fragment targets, and ARIA references. Repeating an ID can cause references to resolve unexpectedly, especially when a component appears several times. I would generate identifiers within a clear scope and connect related attributes consistently rather than use array positions that change unpredictably during updates. Tests should render multiple instances, because a component tested alone can conceal the problem. A class selector or data attribute may be more appropriate when the intent is grouping rather than identity.
72. How do you make a complex table's header relationships clear?
Start by simplifying the table into understandable row and column groups. Use appropriate header cells and scope where the relationships are straightforward; more complex structures may need explicit headers references to IDs. A caption and nearby explanation can describe the table's purpose without replacing cell associations. I would test representative data-cell navigation with assistive technology and examine narrow-screen presentation. Merely adding role="table" or styling cells as headers does not fix a confusing data model or guarantee correct header announcements.
73. What happens when an HTML anchor opens a new tab?
Target="_blank" requests a new browsing context, subject to browser behavior. Modern HTML processing gives such links implicit noopener behavior, but explicitly using rel="noopener" can make the intention clear for relevant compatibility needs. Noreferrer additionally suppresses referrer information and should not be added without considering that effect. I would avoid forcing a new tab unnecessarily and communicate unexpected context changes when they matter. These settings address particular browsing relationships; they do not validate the destination or make an untrusted URL safe.
74. How should canonical links and metadata be used responsibly?
A canonical link identifies a preferred URL for substantially equivalent content, while other metadata describes aspects of the document. I would generate these values from a consistent routing and content model, verify that they point to intended accessible pages, and avoid using canonical markup to disguise unrelated content. Consumers decide how to interpret the signals, so markup does not guarantee indexing or ranking. Deployment redirects, duplicate parameters, and localized variants should be reviewed alongside the HTML rather than treated as isolated tags.
75. How does progressive enhancement influence form design?
Start with a form that can submit to a meaningful server endpoint, then add JavaScript to improve feedback or avoid a full navigation where appropriate. Preserve labels, validation feedback, and recoverable error handling in both paths. I would avoid intercepting submission before the enhancement is ready or making a failed script leave an apparently active button with no outcome. This approach does not require every advanced feature to work without scripts, but the essential task and fallback expectations should be explicit and tested.
76. How can content order differ from visual order, and why does it matter?
CSS can rearrange the visual placement of elements without changing their DOM order. Keyboard traversal and reading order can therefore follow a sequence that differs from what sighted users expect. I would make the source order meaningful first and use layout changes carefully. Adding positive tabindex values to imitate one visual arrangement is a brittle repair that can fail at another breakpoint. Test with keyboard navigation and linear reading, including responsive layouts and error states, rather than relying on a screenshot of the desktop view.
77. How should focus be handled after a dynamic content change?
Keep focus stable when possible, and move it deliberately only when the interaction requires a new context, such as opening a modal dialog or revealing a meaningful error summary. Removing the focused element without a plan can leave users disoriented. I would identify the logical next place, preserve a visible focus indicator, and avoid unexpected autofocus on routine updates. Live announcements and focus movement solve different needs; moving focus merely to announce a small status change can interrupt the user's task unnecessarily.
78. How do HTML fragments and full documents parse differently?
A fragment is parsed in a context, such as a particular element, while a full document follows document-level parsing rules. Table-related markup is a clear example where context affects the resulting nodes. I would not assume assigning a string to an element's innerHTML produces the same tree as loading that string as a complete page. This matters for component rendering, sanitization, and tests. Use a standards-aware parser or the actual browser context and inspect the resulting DOM rather than compare source strings alone.
79. What should you check when a native control looks different across browsers?
First determine whether the difference is presentation or behavior. Native date pickers, selects, and focus indicators can vary while still implementing the relevant control contract. I would test data values, keyboard operation, labeling, validation, and target-device usability before deciding to replace the control. A custom replacement can trade a cosmetic inconsistency for many functional obligations. If a particular feature is essential, document the support requirements and provide an appropriate fallback rather than depend on one browser's appearance as the specification.
80. How can a conformance checker help without replacing manual testing?
A checker can identify invalid nesting, unsupported attributes, duplicate identifiers, and other machine-detectable issues. It cannot determine whether alt text accurately describes an image, whether a form is understandable, or whether a keyboard workflow is usable. I would use it as an early feedback tool and investigate messages against the relevant standard, especially for newer features. Then perform focused browser and accessibility tests. A zero-error report is evidence about checked constraints, not a certificate that the entire page is secure, accessible, or correct.
HTML Interview Questions and Answers for Experienced
These answers focus on production judgment: identify the failing contract, collect evidence, and test a targeted repair. No single tag or automated score proves that a complete experience is correct.
81. How would you diagnose a page whose DOM differs from its HTML source?
I would compare the network response, the parsed DOM before application changes, and the DOM after scripts run. Parser error recovery, server transformations, extensions, and client rendering can produce different explanations. Reduce the problem to a small document and identify the relevant content-model or parsing rule before changing code. A browser inspector shows the current tree, while view-source represents a different layer. I would not assume either is wrong merely because they differ, but I would fix unintended invalid structure rather than depend on repair.
82. Why can invalid table markup produce surprising node placement?
HTML has specialized table insertion modes, and certain misplaced content can be foster-parented outside the table rather than remain where its source position suggests. Browsers may also insert structural elements such as tbody. I would inspect actual parent-child relationships and test a minimal example before debugging selectors or hydration. The correct fix is to produce conforming table structure, not write increasingly complex selectors around accidental repair. Tests based only on string snapshots can miss the tree the browser actually constructs.
83. How can HTML parsing cause a hydration mismatch?
A server-rendered string can be repaired into a DOM that differs from the client framework's expected tree, especially with invalid nesting or table structure. Other causes include inconsistent data, locale-sensitive output, and client-only state. I would compare the server response and browser tree before blaming the framework's diffing algorithm. Fix deterministic rendering and valid structure first, then assess intentional differences through the framework's supported mechanisms. Suppressing warnings without understanding the mismatch can hide lost state, broken event wiring, or inaccessible content.
84. How would you review HTML generated by a CMS or rich-text editor?
I would compare the full saved content with the approved source and inspect headings, lists, links, code text, and image alternatives after reopening. Editors can sanitize, normalize, or drop markup, so an apparently successful paste is not sufficient evidence. Verify both content and semantics, including ordered-list starts and link attributes. I would keep the source artifact and a recoverable readback, then investigate differences rather than weaken comparison rules to accept missing text. Rendering checks and content-parity checks answer complementary questions.
85. What makes HTML injection different from safely displaying text?
An HTML insertion operation asks the browser to parse a string as markup, while a text operation treats the string as characters. Untrusted data passed into an HTML sink can introduce unwanted elements, attributes, or executable behavior. I would use textContent for plain text and a maintained, context-appropriate sanitization policy when rich HTML is truly required. Escaping must match the insertion context, and URL values need their own validation. Avoid ad hoc replacement rules that claim to make arbitrary markup safe.
The variable represents plain text. Rich HTML requires a different, explicitly secured rendering policy.
Expected behavior: The angle-bracket text is displayed literally; it does not create a strong element.
86. Why is removing script tags not enough to sanitize HTML?
Active or dangerous behavior is not limited to script elements. Event-handler attributes, unsafe URL schemes, embedded content, and parser interactions can also matter. A sanitizer must understand allowed elements, attributes, URL policies, and the context in which the result will be parsed. I would use a maintained implementation with a constrained product policy and test representative hostile inputs without exposing real users. Later string manipulation or insertion into a different context can invalidate assumptions, so sanitization belongs within a defined rendering pipeline.
87. What role can Content Security Policy play for HTML pages?
CSP can restrict resource loading and script execution according to a response policy, providing defense in depth against certain injection outcomes. It does not replace safe templating, authorization, or sanitization. I would introduce a carefully designed policy, inspect reports, and address incompatible inline behavior rather than broadly allowing everything to make errors disappear. Delivery method matters: some capabilities are not available through a meta policy. Verify the actual response headers and target-browser behavior, and treat policy violations as evidence to investigate rather than automatic proof of an attack.
88. How do Trusted Types help with DOM injection risks?
Trusted Types can constrain supported DOM injection sinks to values produced through explicit policies, helping centralize and audit dangerous string-to-markup operations. The policies still need to perform appropriate validation or sanitization; wrapping an unsafe string is not protection. I would check support and enforcement in the target browsers and design a fallback security posture that does not rely solely on one API. Migration should identify real sinks and dependencies, with focused tests, rather than create a permissive default policy that silently accepts everything.
89. How would you embed untrusted content with an iframe?
I would isolate it in an appropriate origin and start from restrictive sandboxing, granting only the capabilities the feature actually needs. Combining permissions such as scripts and same-origin access can undermine intended isolation in relevant same-origin scenarios. I would review navigation, forms, downloads, messaging, and resource policies separately, and validate any cross-window messages against explicit expectations. An iframe title helps users identify it but is unrelated to security isolation. Test the exact embedding arrangement instead of treating the presence of sandbox as a universal guarantee.
90. How do you prevent a form's HTML from creating a false sense of security?
I would explain that required, hidden, readonly, disabled, and constrained inputs control browser behavior, not the trustworthiness of incoming requests. The server must independently validate values, authorize the operation, and apply appropriate protections for state-changing requests. Hidden fields are still visible and editable to the client. The HTML should help users submit correct information, while the backend enforces the real rules. Tests should construct requests outside the normal page flow so the team verifies that controls are effective beyond a cooperative browser interface.
91. How would you investigate a field that is visible but missing from submitted data?
I would inspect its name, disabled state, form association, checked or selected state, and the actual submitter. Then compare the constructed entry list and network request with the expected server contract. A JavaScript serializer may also diverge from native submission rules. I would reproduce the smallest failing case and avoid adding a duplicate hidden field without understanding the result, because that can create repeated values or stale data. The fix should preserve intentional absence semantics and be verified across the relevant submission paths.
92. How would you design accessible validation for a long form?
I would provide clear instructions before entry, associate field errors with their controls, and offer a useful summary when submission reveals several problems. Preserve entered values and move focus deliberately when that helps users recover. Error messages should identify the issue and the correction rather than merely say 'invalid.' Native validation can contribute, but the complete workflow needs keyboard and assistive-technology testing. I would also test server-returned errors and partially completed forms, since client-only success does not establish an accessible recovery experience.
93. What should a custom combobox implementation account for?
A custom combobox needs an explicit interaction pattern, accessible name, expanded state, popup relationship, keyboard behavior, focus management, and correct selection semantics. It is much more than a text input beside a visually positioned list. I would first check whether a native select or another simpler control meets the requirement. If custom behavior is justified, follow an appropriate documented pattern and test target browser and assistive-technology combinations. A handful of ARIA attributes cannot compensate for missing keyboard logic or confusing state transitions.
94. How would you decide between a native dialog and a custom overlay?
I would start from the interaction requirements: modality, focus containment, closing behavior, naming, and fallback support. Native dialog can supply important platform behavior, but the application still has to choose initial focus and handle outcomes sensibly. A custom overlay must implement and test those responsibilities explicitly. I would prefer the simpler design that meets the target environments, not assume a visually identical overlay is equivalent. Test nested interactions, canceled actions, and focus restoration after the triggering element changes or disappears.
95. How would you assess accessibility beyond automated checks?
I would test complete user tasks with keyboard navigation, magnification or zoom, meaningful reading order, and representative assistive technologies. Inspect names, roles, states, error recovery, and changes during interaction, not just the initial document. Automated checks are valuable for recurring detectable mistakes, but they cannot judge whether a description is useful or an interaction is understandable. Record the combinations and scenarios tested, involve knowledgeable users where possible, and prioritize barriers by their effect on completing the task rather than by a tool's score alone.
96. How can overly aggressive ARIA make an HTML interface worse?
ARIA can override or add accessibility semantics without implementing behavior. An incorrect role, conflicting label, or inaccurate state can therefore mislead users about what an element is or how it works. I would prefer native HTML where possible and add only supported, necessary semantics. Review the computed accessibility tree and real interaction rather than count attributes. Removing an inappropriate role can be the correct repair. A component should expose the same essential meaning through its visible label, programmatic name, keyboard behavior, and current state.
97. How would you design an icon-only action button?
Use a native button with a concise accessible name describing the action, and ensure the icon does not create a conflicting duplicate name. A visible text label is often better when the action is unfamiliar; a tooltip alone is not a complete naming strategy. I would set the button type deliberately, preserve a visible focus indicator, and verify adequate interaction target sizing through the design. Test toggle state or disabled behavior if applicable, because naming the initial icon does not establish a complete accessible interaction.
Connect the action to the help component in a real application; this fragment demonstrates naming only.
Expected behavior: The button name is Close help, while the decorative symbol does not add a competing name.
98. How do you manage dynamic status messages without disrupting focus?
Use an appropriate status or live-region mechanism for meaningful updates that should be announced while focus remains on the user's current task. Choose urgency carefully and keep messages concise so routine changes do not become constant interruptions. I would create and update the region in a tested way and avoid assuming every insertion will be announced identically by every technology. A status message does not replace a visible result or an error association. Critical decisions may require a different interaction, not merely a more assertive announcement.
99. How would you make a responsive image strategy measurable?
I would define expected display sizes, candidate dimensions, formats, and acceptable visual quality, then inspect actual selected resources and transferred bytes at representative viewport and density combinations. Confirm that sizes matches layout assumptions and that important images are discovered early. Also test alt text, reserved space, and art-direction content equivalence. A long srcset is not evidence of an efficient strategy. Compare loading and layout metrics under realistic conditions, and avoid optimizing file size by removing information users need to understand the image.
100. What can HTML contribute to improving initial rendering performance?
HTML determines early discovery of key resources, useful document structure, and hints such as preload or fetch priority where appropriate. I would ensure important content and resources are discoverable without unnecessary script dependency, then measure the actual bottleneck. Excessive preloading can compete with more important requests, and hints are not commands that guarantee a particular schedule. Image dimensions, sensible script loading, and concise initial markup can help, but HTML changes should be evaluated alongside CSS, network conditions, caching, and server response behavior.
101. How should preload be used without wasting bandwidth?
Preload should identify a resource needed soon that the browser might otherwise discover late, with the correct destination and relevant cross-origin settings. A mismatch can lead to unused or duplicate fetching rather than an improvement. I would measure before adding it, limit it to genuinely important resources, and verify that the consumer can reuse the fetched response. Preload does not execute a script or apply a stylesheet by itself. It is one loading hint, not a substitute for a coherent resource-delivery strategy.
102. How would you evaluate a new HTML feature before adopting it?
I would check the current standard, actual implementation support, known interoperability issues, and the specific behavior the product needs. A feature name appearing in documentation does not prove every subfeature works consistently in all target environments. Build a focused fixture, test the relevant devices and assistive technologies, and define a fallback where necessary. I would distinguish syntax support from usable behavior and avoid relying exclusively on user-agent strings. Adoption should be based on the application's audience and failure tolerance rather than novelty alone.
103. What is progressive enhancement's relationship to feature detection?
Feature detection checks whether a needed capability is available, while progressive enhancement defines how the experience builds on a dependable baseline. They work together but are not identical: an API can exist while a particular behavior remains unsuitable or incomplete. I would test the feature that matters, preserve a functional alternative, and avoid partially replacing native behavior before the enhancement is ready. The fallback should be exercised in tests, because a branch that exists only on paper can fail when a script or resource is unavailable.
104. How would you handle multilingual and bidirectional user content?
I would preserve correct encoding, identify language when known, and use appropriate directionality, including isolation for embedded user text where needed. A person's name or identifier should not unexpectedly reorder surrounding punctuation or numbers. Bdi and dir="auto" can be useful tools, but the design still needs representative mixed-direction testing. I would avoid stripping unfamiliar characters merely to simplify layout and keep validation aligned with the actual data domain. Translation also affects labels, text expansion, and the order in which content is most understandable.
Test real mixed-direction strings, punctuation, and numbers rather than treating one example as complete internationalization coverage.
Expected behavior: The inserted name is directionally isolated from surrounding text.
105. What should a reusable HTML form component guarantee?
It should generate correct label associations, unique IDs, meaningful names, appropriate control types, and clear relationships to help and error text. It should also expose disabled, readonly, required, and invalid states accurately without conflating their meanings. I would test multiple instances, server-rendered output, validation changes, and keyboard use. The component's API should make correct markup the easy path, while allowing necessary domain variations. A visually consistent input wrapper that silently drops submission names or overrides accessible labels is not a reliable abstraction.
106. How would you test a component using shadow DOM?
I would test the component's public interaction and content contract, including slotted content, focus behavior, exposed names, and event handling. Encapsulation changes how selectors and references work, so a test that only inspects light-DOM markup can miss important behavior. I would use supported testing and accessibility inspection tools for the actual component arrangement, not assume shadow boundaries guarantee isolation from all styles or security threats. Native form participation and labels deserve specific checks when a custom element is intended to act as a form control.
107. How can native form participation be added to a custom element?
Form-associated custom elements can use the platform's supported custom-element and ElementInternals facilities to participate in form value and validity behavior. This requires an explicit implementation and compatible target browsers; a custom tag does not become a form control automatically. I would test submission, reset, disabled-state handling, validation, and accessible naming as separate obligations. A hidden-input workaround can be useful in some designs but may not reproduce every native behavior, so document limitations rather than presenting it as complete equivalence.
108. How would you prevent duplicate submissions without breaking forms?
I would provide clear pending feedback and design the server operation to handle retries or repeated requests appropriately. Disabling a button can help interaction, but changing disabled state too early can affect which submitter data is included, and it is not a complete concurrency safeguard. I would preserve keyboard submission paths and recover from failures so users can retry. Test double activation, slow networks, and uncertain outcomes. The HTML should communicate state while the server's idempotency or deduplication policy protects the actual business operation.
109. Why does a valid DOM not necessarily mean safe or correct content?
A parser can construct a well-formed tree from markup that is misleading, inaccessible, or dangerous in its application context. A link can point to an unapproved destination, a form can submit sensitive data incorrectly, and a meaningful-looking heading can still organize the content poorly. I would separate structural conformance, content integrity, accessibility, and security checks. Each needs evidence appropriate to its purpose. Treating successful parsing as approval of everything the document can do leaves important risks and usability problems unexamined.
110. How would you review third-party HTML embeds before integration?
I would identify required scripts, frames, permissions, data flows, and fallback behavior, then assess how they affect the page's performance, privacy, accessibility, and security controls. Vendor-provided markup is not automatically appropriate unchanged. Test the embed with keyboard navigation, blocked resources, and relevant consent states. I would also define ownership and removal procedures so the integration remains maintainable. The review should focus on actual capabilities and transmitted data rather than assume an iframe or a recognizable provider name resolves every concern.
111. How would you investigate a link that behaves incorrectly only after deployment?
I would inspect the resolved URL, document base URL, deployment path, redirects, and server routing. Relative links can work at a local root but resolve differently under nested routes or a subdirectory. A base element or client-side router can also affect the apparent behavior. I would compare the actual anchor destination and network request before changing click handlers. Preserve ordinary browser navigation where possible, and test refreshes, copied links, fragments, and opening in a new tab so the fix covers more than one scripted path.
112. How should forms handle server-side errors after a navigation?
The returned page should preserve appropriate entered values, identify errors clearly, and provide a usable path to correction. Passwords and other sensitive values need deliberate handling rather than unconditional repopulation. I would maintain label and error associations and provide a meaningful document title or heading indicating the result. Focus and error-summary behavior should be tested after the new document loads. A server response that merely prints an error string at the top may communicate failure visually while leaving keyboard and assistive-technology users unsure what to fix.
113. How would you design HTML for printing or nonvisual consumption?
Start with meaningful document order, headings, lists, tables, and text alternatives, then use print-specific CSS where presentation needs to change. Essential content should not depend solely on hover, color, or an expanded interaction that is omitted from output. I would test representative documents, including links and lengthy tables, rather than assume the screen layout will print well. Semantic HTML provides a foundation across contexts, but a print stylesheet and accessible alternatives still require intentional decisions about what information the user needs.
114. What should an HTML-focused performance audit avoid confusing?
It should distinguish HTML structure from CSS layout costs, JavaScript execution, server latency, and network delivery. A large DOM can contribute to work, but raw element count alone does not explain every slow interaction. I would capture a trace or appropriate metrics, identify the bottleneck, and make a targeted change. Replacing meaningful elements with generic containers rarely solves the underlying issue. Performance improvements should preserve accessibility, content completeness, and browser behavior, with before-and-after evidence under comparable conditions.
115. How would you build regression tests for HTML semantics?
I would assert meaningful outcomes such as control names, form entries, heading hierarchy, landmark availability, and keyboard navigation, using tools appropriate to each layer. Static source checks help with patterns, while browser tests verify parsing and interaction. Avoid snapshotting enormous strings without checking the behavior users rely on. Include repeated components, invalid input, and changed state. Tests should fail when a real contract breaks, such as a label pointing to the wrong control, rather than merely when harmless whitespace changes.
116. How would you migrate old presentational markup to modern HTML?
I would identify the content meaning and current behavior before replacing deprecated or purely presentational structures. Move visual styling into CSS while preserving links, form values, focus order, and accessible relationships. A broad tag substitution can change layout or behavior unexpectedly, so migrate representative components and test them before scaling. I would also remove invalid nesting and duplicate IDs where the scope permits. Success is a maintained or improved user experience and clearer structure, not simply a source file containing newer element names.
117. How would you debug a page that works with a mouse but fails with a keyboard?
I would follow the complete task using Tab, Shift+Tab, Enter, Space, and relevant widget keys, noting where focus becomes invisible, trapped, or disconnected from the action. Then inspect native element choice, event handling, tabindex, and hidden or inert ancestors. A mouse click listener on a div is a common clue, but the investigation should follow evidence. Fix the interaction model rather than add isolated key handlers indiscriminately, and retest closing, cancellation, and error paths as well as the happy path.
118. How would you evaluate an HTML answer that relies on outdated browser myths?
I would ask for the relevant standard or current compatibility evidence and reproduce the claim with a small fixture. Common examples include assuming every script blocks identically, every nested section gets a reliable automatic heading outline, or every custom control needs ARIA instead of native markup. Historical behavior can explain old code but should not be presented as a current universal rule. I would reward candidates who state assumptions and revise their answer when evidence changes, rather than those who confidently repeat an obsolete simplification.
119. How would you design a practical senior HTML interview exercise?
I would provide a small page with a mislabeled form field, an action implemented as a link, invalid nesting, and an unclear error state. Ask the candidate to identify user impact, inspect the parsed tree, and propose minimal repairs with tests. Then introduce a responsive image or dialog requirement to discuss trade-offs. Strong candidates distinguish semantics, styling, scripting, and server responsibilities. The exercise should evaluate reasoning and accessible behavior rather than reward memorization of every element or a wholesale rewrite without diagnosis.
120. What does a strong production HTML review cover?
It covers meaningful structure, correct parsing, clear names and relationships, native interaction, and the behavior of forms and resources. I would also review untrusted-content handling, responsive and multilingual cases, fallback paths, and support for the intended browsers and assistive technologies. Use automated conformance checks and focused manual tasks together, retaining evidence of what was tested. A production-ready result is not merely markup that renders once; it is a document whose content, interaction, and failure behavior remain understandable and dependable across the supported contexts.
HTML Documentation and Further Reading
Use these primary standards and WAI references to verify element contracts, parsing, accessibility relationships, and interaction requirements. Implementation support and usability still require testing in the environments your application supports.
Similar Posts
