HTML Interview Questions
Q1. What is HTML?
HTML (HyperText Markup Language) is the standard markup language for creating web pages. It describes the structure of web pages using markup.
Q2. What are the new features in HTML5?
HTML5 introduced several new features including semantic elements, form improvements, and multimedia support.
<!-- Semantic Elements -->
<header>
<nav>
<main>
<article>
<section>
<footer>
<!-- Multimedia -->
<audio>
<video>
<canvas>
Q3. What are semantic elements in HTML5?
Semantic elements are HTML elements that carry meaning about their content structure, making the code more readable and helping search engines better understand the content.
Q4. Explain the difference between <div> and <span>
div is a block-level element used for grouping larger sections, while span is an inline element used for smaller portions of text.
<div>Block level element</div>
<span>Inline element</span>
Q5. What is the purpose of the DOCTYPE declaration?
The DOCTYPE declaration helps browsers render the page in standards mode, specifying which version of HTML is being used in the document.
<!DOCTYPE html>
<html lang="en">
<!-- HTML5 DOCTYPE declaration -->
</html>
Q6. Explain the difference between <script>, <script async>, and <script defer>
script loads and executes immediately, async loads and executes when available without blocking, and defer loads in the background but executes after HTML parsing.
<!-- Standard script (blocks parsing) -->
<script src="script.js"></script>
<!-- Async script (executes as soon as downloaded) -->
<script async src="analytics.js"></script>
<!-- Defer script (waits for HTML parsing) -->
<script defer src="main.js"></script>
Q7. What are meta tags and why are they important?
Meta tags provide metadata about the HTML document, crucial for SEO, defining character set, page description, and viewport settings for responsive design.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page description for search engines">
</head>
Q8. Explain HTML form validation attributes
HTML5 introduced built-in form validation attributes like required, min, max, pattern to validate user input directly in the browser without JavaScript.
<form>
<input type="text" required minlength="3" maxlength="10">
<input type="email" required>
<input type="number" min="0" max="100">
<input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
</form>
Q9. What are data attributes in HTML?
Data attributes allow storing custom data directly in HTML elements, which can be accessed and manipulated using JavaScript.
<div data-user-id="123"
data-role="admin"
data-last-login="2024-01-15">
Custom User Information
</div>
Q10. Explain HTML accessibility attributes
Accessibility attributes like aria-label, role, and alt help screen readers and assistive technologies understand and navigate web content.
<button aria-label="Close menu">X</button>
<img src="graph.png" alt="Monthly sales chart">
<div role="alert">Warning message</div>
Q11. What is the difference between <strong> and <b>, <em> and <i>?
While visually similar, strong/em carry semantic meaning (importance/emphasis), whereas b/i are purely presentational.
<strong>Important text</strong>
<b>Visually bold text</b>
<em>Emphasized text</em>
<i>Italicized text</i>
Q12. How do you create responsive images?
Use srcset and sizes attributes to provide multiple image sources for different screen sizes and resolutions.
<img src="small.jpg"
srcset="small.jpg 500w,
medium.jpg 1000w,
large.jpg 1500w"
sizes="(max-width: 600px) 500px,
(max-width: 1200px) 1000px,
1500px"
alt="Responsive image">
Q13. Explain HTML5 input types
HTML5 introduced new input types that provide better mobile and desktop validation and user experience.
<input type="date">
<input type="time">
<input type="email">
<input type="url">
<input type="color">
<input type="range">
Q14. What are HTML entities?
HTML entities are special codes used to represent reserved characters, invisible characters, and characters that are difficult to type.
< represents <
> represents >
& represents &
© represents ©
€ represents €
Q15. Explain the picture element
The picture element allows specifying multiple sources for an image, enabling responsive and art-directed image loading.
<picture>
<source media="(min-width: 800px)" srcset="large.jpg">
<source media="(min-width: 400px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive image">
</picture>
Q16. What is the Shadow DOM?
Shadow DOM is a web standard that allows encapsulation of styling and markup in web components, preventing style and script conflicts.
<div id="host">
<template id="shadow-content">
<style>/* Encapsulated styles */</style>
<div>Shadow DOM Content</div>
</template>
</div>
<script>
const host = document.getElementById('host');
const shadowRoot = host.attachShadow({mode: 'open'});
shadowRoot.innerHTML =
document.getElementById('shadow-content').innerHTML;
</script>
Q17. What are Web Components?
Web Components are a set of web platform APIs that allow you to create reusable custom elements with their own functionality and styling encapsulation.
class CustomButton extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<button>Custom Web Component</button>
`;
}
}
customElements.define('custom-button', CustomButton);
Q18. Explain the difference between localStorage and sessionStorage
localStorage persists data even after the browser is closed, while sessionStorage stores data only for the duration of the page session.
// localStorage (persists across browser sessions)
localStorage.setItem('username', 'JohnDoe');
// sessionStorage (cleared when tab is closed)
sessionStorage.setItem('tempData', 'Temporary Information');
Q19. What are the main accessibility ARIA roles?
ARIA roles provide semantic meaning to elements, helping assistive technologies understand the structure and functionality of web content.
<div role="navigation">Site Navigation</div>
<div role="alert">Important Notification</div>
<div role="dialog">Modal Window</div>
<div role="tabpanel">Tab Content</div>
Q20. How do you implement HTML5 drag and drop?
HTML5 provides native drag and drop APIs that allow elements to be dragged and dropped between different containers.
<div
draggable="true"
ondragstart="event.dataTransfer.setData('text/plain', event.target.id)"
>
Draggable Element
</div>
<div
ondrop="dropHandler(event)"
ondragover="allowDrop(event)"
>
Drop Target
</div>
Q21. Explain the details and summary elements
The details and summary elements create an interactive disclosure widget that can show or hide additional information.
<details>
<summary>Click to expand</summary>
<p>Hidden content that can be revealed</p>
</details>
Q22. What are HTML5 custom data attributes?
Custom data attributes allow storing additional information directly in HTML elements that can be accessed via JavaScript.
<article
data-author="John Doe"
data-published-date="2024-01-15"
>
Blog Post Content
</article>
<script>
const article = document.querySelector('article');
console.log(article.dataset.author);
</script>
Q23. Explain the content attribute in meta tags
The content attribute in meta tags provides specific information about the webpage, crucial for SEO and social media sharing.
<head>
<meta name="description" content="Comprehensive guide to HTML5 features">
<meta property="og:title" content="HTML5 Advanced Tutorial">
<meta property="og:type" content="article">
</head>
Q24. How do you create responsive typography?
Use viewport units and CSS clamp() to create fluid typography that scales smoothly across different screen sizes.
<style>
h1 {
font-size: clamp(2rem, 5vw, 4rem);
}
</style>
<h1>Responsive Heading</h1>
Q25. What are HTML template tags?
The template tag allows you to declare fragments of HTML that can be cloned and inserted into the document by script.
<template id="user-template">
<div class="user-card">
<img src="" alt="User Avatar">
<h2></h2>
<p></p>
</div>
</template>
<script>
const template = document.getElementById('user-template');
const clone = template.content.cloneNode(true);
// Populate and insert the clone
</script>
Q26. What is the difference between localStorage, sessionStorage, and Cookies?
localStorage persists data indefinitely, sessionStorage stores data for a browser session, while cookies have expiration and are sent with every HTTP request.
// localStorage (permanent storage)
localStorage.setItem('theme', 'dark');
// sessionStorage (page session)
sessionStorage.setItem('tempData', 'Session specific');
// Cookies (with expiration)
document.cookie = 'username=JohnDoe; expires=Thu, 18 Dec 2024 12:00:00 UTC';
Q27. Explain the Critical Rendering Path in HTML and Browser Rendering
The Critical Rendering Path is the sequence of steps the browser goes through to convert HTML, CSS, and JavaScript into rendered pixels on the screen.
// Optimization techniques
<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">
<script defer src="app.js"></script>
Q28. What are the performance implications of using many div elements?
Excessive div usage can increase DOM complexity, negatively impacting rendering performance and memory consumption.
// Semantic alternative
<header>
<nav>
<ul>
<li><a href="#">Home</a></li>
</ul>
</nav>
</header>
Q29. Explain HTML Preload, Prefetch, and Preconnect
These resource hints help browsers optimize resource loading and improve page performance by giving early hints about critical resources.
<head>
<!-- Preload critical resources -->
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="main.js" as="script">
<!-- Prefetch resources for future navigation -->
<link rel="prefetch" href="next-page.html">
<!-- Preconnect to critical domains -->
<link rel="preconnect" href="https://fonts.googleapis.com">
</head>
Q30. What are the security risks of innerHTML and how to mitigate them?
innerHTML can introduce cross-site scripting (XSS) vulnerabilities by directly inserting unescaped HTML content.
// Unsafe
element.innerHTML = userInput;
// Safe methods
// 1. TextContent
element.textContent = userInput;
// 2. DOMPurify library
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
Q31. Explain the difference between async and defer script loading
Async scripts download and execute immediately without blocking, while defer scripts download in background and execute after HTML parsing.
<!-- Async: Downloads and executes immediately -->
<script async src="analytics.js"></script>
<!-- Defer: Waits for HTML parsing before execution -->
<script defer src="main.js"></script>
Q32. What are Web Workers and how do they improve performance?
Web Workers allow running scripts in background threads, preventing long-running tasks from blocking the main UI thread.
// Main thread
const worker = new Worker('worker.js');
worker.postMessage({ data: largeDataset });
worker.onmessage = function(event) {
console.log('Processed result:', event.data);
};
// worker.js
self.onmessage = function(event) {
// Perform heavy computation
const result = processData(event.data);
self.postMessage(result);
};
Q33. Explain Content Security Policy (CSP)
CSP is a security layer that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks.
<!-- In HTTP Header -->
Content-Security-Policy:
default-src 'self';
script-src 'self' https://trusted.cdn.com;
style-src 'self' https://fonts.googleapis.com;
Q34. What are the performance considerations for responsive images?
Use srcset and sizes attributes to serve appropriately sized images, reducing unnecessary bandwidth consumption.
<img src="small.jpg"
srcset="small.jpg 500w,
medium.jpg 1000w,
large.jpg 1500w"
sizes="(max-width: 600px) 500px,
(max-width: 1200px) 1000px,
1500px"
alt="Responsive image">
Q35. Explain the Intersection Observer API
Provides an efficient way to detect when an element enters or leaves the viewport, useful for lazy loading and infinite scrolling.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Load content or trigger action
entry.target.classList.add('visible');
}
});
});
observer.observe(document.querySelector('.lazy-load'));
Q36. What are the accessibility considerations for form design?
Implement proper labeling, error handling, and keyboard navigation to ensure forms are usable by all users, including those using assistive technologies.
<form>
<label for="email">Email Address</label>
<input
type="email"
id="email"
name="email"
required
aria-describedby="email-error"
>
<span id="email-error" role="alert">
Please enter a valid email
</span>
</form>
Q37. Explain HTML Custom Elements and Shadow DOM
Custom Elements allow creating new HTML tags with custom behavior, while Shadow DOM provides encapsulation for styling and markup.
class CustomTooltip extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
const tooltip = document.createElement('div');
tooltip.textContent = this.getAttribute('text');
shadow.appendChild(tooltip);
}
}
customElements.define('custom-tooltip', CustomTooltip);
Q38. What are the performance implications of layout thrashing?
Layout thrashing occurs when JavaScript repeatedly reads and writes to the DOM, causing multiple reflows which are computationally expensive.
// Inefficient (Causes layout thrashing)
elements.forEach(el => {
el.style.height = `${el.offsetHeight * 2}px`;
});
// Efficient (Batch reads and writes)
const heights = elements.map(el => el.offsetHeight);
elements.forEach((el, index) => {
el.style.height = `${heights[index] * 2}px`;
});
Q39. Explain Server-Sent Events (SSE)
SSE allows servers to push real-time updates to the client over a single HTTP connection, ideal for live feeds and notifications.
// Client-side
const eventSource = new EventSource('/updates');
eventSource.onmessage = (event) => {
console.log('New update:', event.data);
};
// Server-side (example)
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-open'
});
res.write(`data: ${JSON.stringify(update)}
`);
Q40. What are the best practices for form validation?
Implement both client-side and server-side validation, use HTML5 validation attributes, and provide clear, accessible error messages.
<form novalidate>
<input
type="email"
required
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$"
title="Please enter a valid email address"
>
<button type="submit">Submit</button>
</form>
Q41. Explain the differences between HTTP/1.1 and HTTP/2
HTTP/2 introduces multiplexing, server push, and header compression to improve web performance compared to HTTP/1.1.
// HTTP/2 benefits demonstrated conceptually
// Multiplexing multiple requests over single connection
// Server push of resources
// Compressed headers
Q42. What are the performance benefits of using the Picture element?
The picture element allows serving different image sources based on device characteristics, reducing unnecessary image downloads.
<picture>
<source media="(min-width: 1200px)" srcset="large.webp" type="image/webp">
<source media="(min-width: 800px)" srcset="medium.jpg">
<img src="small.png" alt="Responsive image">
</picture>