Navigation

GyaanSetu Educational Platform

Top 20 HTML Interview Questions for 2026

Master semantic HTML, accessibility, SEO, forms, and modern HTML5 features

Semantic HTMLAccessibilitySEOHTML5
1

What is semantic HTML and why is it important?

Semantic HTML uses tags that convey meaning about the content they contain, rather than just presentation. Examples include <header>, <nav>, <article>, <section>, <aside>, <footer>, instead of generic <div>. Benefits include: better accessibility for screen readers, improved SEO as search engines understand content structure, easier maintenance and readability, and better default styling. Semantic HTML makes your code self-documenting and improves the overall web experience.

example.js
1<!-- Non-semantic HTML (Bad) -->
2<div class="header">
3 <div class="nav">
4 <div class="nav-item">Home</div>
5 <div class="nav-item">About</div>
6 </div>
7</div>
8<div class="content">
9 <div class="article">
10 <div class="title">Article Title</div>
11 <div class="text">Article content...</div>
12 </div>
13</div>
14
15<!-- Semantic HTML (Good) -->
16<header>
17 <nav>
18 <a href="/">Home</a>
19 <a href="/about">About</a>
20 </nav>
21</header>
22<main>
23 <article>
24 <h1>Article Title</h1>
25 <p>Article content...</p>
26 </article>
27</main>
28<footer>
29 <p>&copy; 2026 Company Name</p>
30</footer>
2

What's the difference between <div> and <span>?

<div> is a block-level element that takes up the full width available and starts on a new line. It's used for grouping larger sections of content. <span> is an inline element that only takes up as much width as necessary and doesn't start on a new line. It's used for styling small portions of text or content within a line. Both are generic containers with no semantic meaning.

example.js
1<!-- Block-level element (div) -->
2<div style="background: lightblue; padding: 10px;">
3 This is a div. It takes the full width.
4</div>
5<div style="background: lightgreen; padding: 10px;">
6 This div starts on a new line.
7</div>
8
9<!-- Inline element (span) -->
10<p>
11 This is a paragraph with
12 <span style="color: red;">red text</span>
13 and
14 <span style="font-weight: bold;">bold text</span>
15 inline.
16</p>
17
18<!-- Common use cases -->
19<div class="container">
20 <div class="card">
21 <h2>Card Title</h2>
22 <p>Card content with <span class="highlight">highlighted</span> text.</p>
23 </div>
24</div>
3

What are HTML5 semantic elements?

HTML5 introduced semantic elements that clearly describe their meaning to both browsers and developers. Key elements include: <header> (page/section header), <nav> (navigation links), <main> (main content), <article> (independent content), <section> (thematic grouping), <aside> (sidebar content), <footer> (page/section footer), <figure> and <figcaption> (images with captions), <time> (dates/times), <mark> (highlighted text). These improve accessibility, SEO, and code readability.

example.js
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>HTML5 Semantic Structure</title>
6</head>
7<body>
8 <header>
9 <h1>Website Name</h1>
10 <nav>
11 <ul>
12 <li><a href="/">Home</a></li>
13 <li><a href="/blog">Blog</a></li>
14 <li><a href="/contact">Contact</a></li>
15 </ul>
16 </nav>
17 </header>
18
19 <main>
20 <article>
21 <header>
22 <h2>Article Title</h2>
23 <time datetime="2026-01-31">January 31, 2026</time>
24 </header>
25 <section>
26 <h3>Introduction</h3>
27 <p>Article introduction with <mark>important</mark> content.</p>
28 </section>
29 <figure>
30 <img src="image.jpg" alt="Description">
31 <figcaption>Image caption</figcaption>
32 </figure>
33 </article>
34
35 <aside>
36 <h3>Related Articles</h3>
37 <ul>
38 <li><a href="/article1">Article 1</a></li>
39 <li><a href="/article2">Article 2</a></li>
40 </ul>
41 </aside>
42 </main>
43
44 <footer>
45 <p>&copy; 2026 Company. All rights reserved.</p>
46 </footer>
47</body>
48</html>
4

What is the difference between <script>, <script async>, and <script defer>?

Regular <script> blocks HTML parsing until the script is downloaded and executed. <script async> downloads the script in parallel with HTML parsing and executes immediately when ready (may execute out of order). <script defer> downloads in parallel but executes only after HTML parsing is complete, in order of appearance. Use defer for scripts that depend on DOM or other scripts, async for independent scripts like analytics, and regular script only when execution order before DOM matters.

example.js
1<!-- Regular script - blocks HTML parsing -->
2<script src="script.js"></script>
3<!-- HTML parsing blocked until script loads and executes -->
4
5<!-- Async - downloads parallel, executes immediately when ready -->
6<script src="analytics.js" async></script>
7<!-- Good for independent scripts, may execute out of order -->
8
9<!-- Defer - downloads parallel, executes after HTML parsing -->
10<script src="main.js" defer></script>
11<!-- Maintains order, waits for DOM to be ready -->
12
13<!-- Example usage -->
14<!DOCTYPE html>
15<html>
16<head>
17 <!-- Analytics (independent, can run anytime) -->
18 <script src="analytics.js" async></script>
19</head>
20<body>
21 <div id="app"></div>
22
23 <!-- Main app script (needs DOM to be ready) -->
24 <script src="app.js" defer></script>
25
26 <!-- Library that app.js depends on -->
27 <script src="library.js" defer></script>
28 <!-- defer maintains order: library.js → app.js -->
29</body>
30</html>
31
32<!-- Loading timeline comparison -->
33<!--
34Regular: HTML → Block → Download script → Execute → Continue HTML
35Async: HTML + Download → Execute when ready → Continue HTML
36Defer: HTML + Download → HTML complete → Execute in order
37-->
5

What are data attributes and how are they used?

Data attributes (data-*) allow you to store custom data on HTML elements without using non-standard attributes or extra properties in the DOM. They start with 'data-' followed by your custom name. Accessible via JavaScript using dataset property or getAttribute(). Used for storing state, configuration, or metadata that doesn't have a standard HTML attribute. They don't affect layout or styling unless explicitly targeted with CSS. Common in frameworks for storing component state or identifiers.

example.js
1<!-- HTML with data attributes -->
2<article
3 data-id="123"
4 data-category="technology"
5 data-author="John Doe"
6 data-published="2026-01-31"
7 data-likes="42">
8 <h2>Article Title</h2>
9 <p>Article content...</p>
10</article>
11
12<button
13 data-action="delete"
14 data-item-id="456"
15 data-confirm="Are you sure?">
16 Delete
17</button>
18
19<!-- Accessing with JavaScript -->
20<script>
21 const article = document.querySelector('article');
22
23 // Using dataset (camelCase for multi-word attributes)
24 console.log(article.dataset.id); // "123"
25 console.log(article.dataset.category); // "technology"
26 console.log(article.dataset.author); // "John Doe"
27
28 // Setting data attributes
29 article.dataset.views = "100";
30 article.dataset.featured = "true";
31
32 // Using getAttribute/setAttribute
33 console.log(article.getAttribute('data-published'));
34 article.setAttribute('data-status', 'published');
35
36 // Event delegation example
37 document.addEventListener('click', (e) => {
38 if (e.target.dataset.action === 'delete') {
39 const itemId = e.target.dataset.itemId;
40 const confirm = e.target.dataset.confirm;
41 if (window.confirm(confirm)) {
42 deleteItem(itemId);
43 }
44 }
45 });
46</script>
47
48<!-- CSS styling with data attributes -->
49<style>
50 [data-category="technology"] {
51 border-left: 3px solid blue;
52 }
53
54 [data-featured="true"] {
55 background: gold;
56 }
57</style>
6

What is the difference between <strong> and <b>, <em> and <i>?

<strong> indicates strong importance, seriousness, or urgency (semantic). <b> is for stylistically offset text without importance (presentational). <em> indicates emphasis that changes sentence meaning (semantic). <i> is for alternate voice, technical terms, foreign words (presentational). Use semantic tags (<strong>, <em>) when the meaning matters, presentational tags (<b>, <i>) for styling only. Screen readers recognize semantic tags and convey importance through intonation.

example.js
1<!-- Semantic tags (preferred for meaning) -->
2<p>
3 This is <strong>very important</strong> information!
4 <!-- Screen readers emphasize this -->
5</p>
6
7<p>
8 I <em>really</em> mean it.
9 <!-- Changes meaning: "I really mean it" vs "I mean it" -->
10</p>
11
12<!-- Presentational tags (for styling only) -->
13<p>
14 The term <b>HTML</b> stands for HyperText Markup Language.
15 <!-- Just visually bold, no semantic importance -->
16</p>
17
18<p>
19 The word <i>bonjour</i> is French for "hello."
20 <!-- Italic for foreign word, but no emphasis -->
21</p>
22
23<!-- Practical examples -->
24<article>
25 <h1>Travel Guide to Paris</h1>
26
27 <!-- Strong for warnings/important info -->
28 <p>
29 <strong>Warning:</strong> The museum is closed on Mondays.
30 </p>
31
32 <!-- Em for emphasis -->
33 <p>
34 You <em>must</em> try the croissants at this bakery.
35 </p>
36
37 <!-- B for keywords -->
38 <p>
39 <b>Paris</b> is known as the City of Light.
40 </p>
41
42 <!-- I for foreign terms -->
43 <p>
44 Order a <i>café au lait</i> at any café.
45 </p>
46</article>
47
48<!-- Nested usage -->
49<p>
50 <strong>Important: <em>All</em> users must update their passwords.</strong>
51 <!-- Both strong importance AND emphasis on "All" -->
52</p>
7

What are the different types of lists in HTML?

HTML has three types of lists: Ordered lists (<ol>) for numbered items, Unordered lists (<ul>) for bulleted items, and Description lists (<dl>) for term-definition pairs. List items use <li> for ol/ul, <dt> (term) and <dd> (definition) for dl. Lists can be nested, styled with CSS, and have attributes like type, start, and reversed. Choose based on content meaning: ol for sequential steps, ul for non-sequential items, dl for glossaries or key-value pairs.

example.js
1<!-- Ordered List (numbered) -->
2<ol>
3 <li>First item</li>
4 <li>Second item</li>
5 <li>Third item</li>
6</ol>
7
8<!-- Ordered list with attributes -->
9<ol type="A" start="3">
10 <li>Item C</li>
11 <li>Item D</li>
12 <li>Item E</li>
13</ol>
14
15<!-- Reversed ordered list -->
16<ol reversed>
17 <li>Third place</li>
18 <li>Second place</li>
19 <li>First place</li>
20</ol>
21
22<!-- Unordered List (bullets) -->
23<ul>
24 <li>Milk</li>
25 <li>Eggs</li>
26 <li>Bread</li>
27</ul>
28
29<!-- Nested lists -->
30<ul>
31 <li>Frontend
32 <ul>
33 <li>HTML</li>
34 <li>CSS</li>
35 <li>JavaScript</li>
36 </ul>
37 </li>
38 <li>Backend
39 <ul>
40 <li>Node.js</li>
41 <li>Python</li>
42 </ul>
43 </li>
44</ul>
45
46<!-- Description List (term-definition pairs) -->
47<dl>
48 <dt>HTML</dt>
49 <dd>HyperText Markup Language - structure of web pages</dd>
50
51 <dt>CSS</dt>
52 <dd>Cascading Style Sheets - styling of web pages</dd>
53
54 <dt>JavaScript</dt>
55 <dd>Programming language for interactive web pages</dd>
56</dl>
57
58<!-- Multiple definitions for one term -->
59<dl>
60 <dt>Firefox</dt>
61 <dt>Chrome</dt>
62 <dd>Modern web browsers</dd>
63
64 <dt>SEO</dt>
65 <dd>Search Engine Optimization</dd>
66 <dd>Practice of improving website visibility in search results</dd>
67</dl>
8

What are HTML forms and form validation attributes?

HTML forms collect user input using <form> and input elements. HTML5 introduced built-in validation attributes: required (mandatory field), pattern (regex validation), min/max (number/date limits), minlength/maxlength (text length), type (email, url, tel, etc. for automatic validation). Additional attributes include placeholder, autocomplete, autofocus, and disabled. Client-side validation improves UX but always validate server-side for security. The novalidate attribute disables browser validation.

example.js
1<!-- Basic form with validation -->
2<form action="/submit" method="POST">
3 <!-- Required field -->
4 <label for="name">Name (required):</label>
5 <input
6 type="text"
7 id="name"
8 name="name"
9 required
10 minlength="2"
11 maxlength="50"
12 placeholder="Enter your name">
13
14 <!-- Email validation -->
15 <label for="email">Email:</label>
16 <input
17 type="email"
18 id="email"
19 name="email"
20 required
21 placeholder="user@example.com">
22
23 <!-- Pattern validation (phone number) -->
24 <label for="phone">Phone:</label>
25 <input
26 type="tel"
27 id="phone"
28 name="phone"
29 pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
30 placeholder="123-456-7890"
31 title="Format: 123-456-7890">
32
33 <!-- Number with min/max -->
34 <label for="age">Age:</label>
35 <input
36 type="number"
37 id="age"
38 name="age"
39 min="18"
40 max="100"
41 step="1"
42 required>
43
44 <!-- Date with min/max -->
45 <label for="date">Appointment Date:</label>
46 <input
47 type="date"
48 id="date"
49 name="date"
50 min="2026-01-01"
51 max="2026-12-31">
52
53 <!-- URL validation -->
54 <label for="website">Website:</label>
55 <input
56 type="url"
57 id="website"
58 name="website"
59 placeholder="https://example.com">
60
61 <!-- Password with pattern -->
62 <label for="password">Password:</label>
63 <input
64 type="password"
65 id="password"
66 name="password"
67 pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
68 title="Must contain at least one number, one uppercase and lowercase letter, and at least 8 characters"
69 required>
70
71 <!-- Select with required -->
72 <label for="country">Country:</label>
73 <select id="country" name="country" required>
74 <option value="">Select a country</option>
75 <option value="us">United States</option>
76 <option value="uk">United Kingdom</option>
77 <option value="ca">Canada</option>
78 </select>
79
80 <!-- Checkbox required -->
81 <label>
82 <input type="checkbox" name="terms" required>
83 I agree to the terms and conditions
84 </label>
85
86 <!-- Submit button -->
87 <button type="submit">Submit</button>
88</form>
89
90<!-- Form with novalidate (disable browser validation) -->
91<form action="/submit" method="POST" novalidate>
92 <!-- Custom JavaScript validation will be used -->
93</form>
9

What is the purpose of the DOCTYPE declaration?

The DOCTYPE (Document Type Declaration) tells the browser which version of HTML the page is written in, triggering the correct rendering mode. <!DOCTYPE html> is the HTML5 DOCTYPE and should be the first line in every HTML document. Without a DOCTYPE, browsers render in 'quirks mode' with inconsistent behavior. The DOCTYPE is case-insensitive and has no closing tag. It's not an HTML tag but an instruction to the browser. Always include it to ensure standards mode rendering.

example.js
1<!-- HTML5 DOCTYPE (modern, recommended) -->
2<!DOCTYPE html>
3<html lang="en">
4<head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Page Title</title>
8</head>
9<body>
10 <h1>Hello World</h1>
11</body>
12</html>
13
14<!-- HTML 4.01 Strict DOCTYPE (legacy) -->
15<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
16"http://www.w3.org/TR/html4/strict.dtd">
17
18<!-- XHTML 1.0 Strict DOCTYPE (legacy) -->
19<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
20"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
21
22<!-- Why DOCTYPE matters -->
23<!--
24Without DOCTYPE:
25- Browser renders in "Quirks Mode"
26- Inconsistent CSS rendering
27- JavaScript issues
28- Different box model calculations
29
30With DOCTYPE:
31- Browser renders in "Standards Mode"
32- Consistent, predictable rendering
33- Modern features work correctly
34- Better cross-browser compatibility
35-->
36
37<!-- Common mistakes -->
38<!-- ❌ Wrong: Missing DOCTYPE -->
39<html>
40<head>...</head>
41</html>
42
43<!-- ❌ Wrong: DOCTYPE not first -->
44<html>
45<!DOCTYPE html>
46<head>...</head>
47</html>
48
49<!-- ✅ Correct: DOCTYPE first -->
50<!DOCTYPE html>
51<html>
52<head>...</head>
53</html>
10

What are meta tags and their importance?

Meta tags provide metadata about the HTML document - information about the page that's not displayed but used by browsers, search engines, and social media. Key meta tags include: charset (character encoding), viewport (responsive design), description (SEO summary), keywords (search terms), author, robots (crawler instructions), Open Graph (social media sharing), and Twitter Cards. They're placed in <head> and crucial for SEO, accessibility, and social media optimization.

example.js
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <!-- Character encoding (always first in head) -->
5 <meta charset="UTF-8">
6
7 <!-- Viewport for responsive design (required for mobile) -->
8 <meta name="viewport" content="width=device-width, initial-scale=1.0">
9
10 <!-- SEO meta tags -->
11 <meta name="description" content="Learn web development with our comprehensive tutorials on HTML, CSS, and JavaScript. Free resources for beginners and advanced developers.">
12 <meta name="keywords" content="web development, HTML, CSS, JavaScript, tutorials">
13 <meta name="author" content="John Doe">
14 <meta name="robots" content="index, follow">
15
16 <!-- No caching -->
17 <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
18 <meta http-equiv="Expires" content="0">
19
20 <!-- Redirect after 5 seconds -->
21 <meta http-equiv="refresh" content="5;url=https://example.com">
22
23 <!-- Open Graph for social media (Facebook, LinkedIn) -->
24 <meta property="og:title" content="Amazing Article Title">
25 <meta property="og:description" content="This is an amazing article you should read.">
26 <meta property="og:image" content="https://example.com/image.jpg">
27 <meta property="og:url" content="https://example.com/article">
28 <meta property="og:type" content="article">
29 <meta property="og:site_name" content="My Website">
30
31 <!-- Twitter Card -->
32 <meta name="twitter:card" content="summary_large_image">
33 <meta name="twitter:site" content="@username">
34 <meta name="twitter:title" content="Amazing Article Title">
35 <meta name="twitter:description" content="This is an amazing article you should read.">
36 <meta name="twitter:image" content="https://example.com/image.jpg">
37
38 <!-- Theme color for mobile browsers -->
39 <meta name="theme-color" content="#3498db">
40
41 <!-- App-specific meta tags -->
42 <meta name="apple-mobile-web-app-capable" content="yes">
43 <meta name="apple-mobile-web-app-status-bar-style" content="black">
44
45 <!-- Favicon -->
46 <link rel="icon" type="image/x-icon" href="/favicon.ico">
47
48 <title>Page Title - Site Name</title>
49</head>
50<body>
51 <!-- Content here -->
52</body>
53</html>
11

What is the difference between inline and block elements?

Block elements take up the full width available and start on a new line (e.g., <div>, <p>, <h1>-<h6>, <ul>, <ol>, <section>, <article>). Inline elements only take up as much width as necessary and don't start on a new line (e.g., <span>, <a>, <strong>, <em>, <img>). Block elements can contain inline and other block elements, while inline elements should only contain data and other inline elements. This can be changed with CSS display property.

example.js
1<!-- Block-level elements -->
2<div>This is a div (block)</div>
3<div>This div starts on a new line</div>
4
5<p>This is a paragraph (block)</p>
6<p>Another paragraph on a new line</p>
7
8<h1>Heading (block)</h1>
9<section>Section (block)</section>
10<article>Article (block)</article>
11
12<!-- Inline elements -->
13<p>
14 This paragraph contains
15 <span>a span (inline)</span>,
16 <a href="#">a link (inline)</a>,
17 <strong>bold text (inline)</strong>, and
18 <em>italic text (inline)</em>
19 all on the same line.
20</p>
21
22<!-- Block elements list -->
23<!--
24<div>, <p>, <h1>-<h6>, <ul>, <ol>, <li>,
25<table>, <form>, <header>, <footer>,
26<section>, <article>, <nav>, <aside>,
27<main>, <blockquote>, <pre>, <hr>
28-->
29
30<!-- Inline elements list -->
31<!--
32<span>, <a>, <strong>, <em>, <b>, <i>,
33<u>, <img>, <input>, <button>, <label>,
34<select>, <textarea>, <code>, <mark>,
35<small>, <sub>, <sup>
36-->
37
38<!-- Changing display with CSS -->
39<style>
40 /* Make inline element behave as block */
41 span.block {
42 display: block;
43 width: 100%;
44 background: lightblue;
45 }
46
47 /* Make block element behave as inline */
48 div.inline {
49 display: inline;
50 background: lightgreen;
51 }
52
53 /* Inline-block: best of both worlds */
54 .inline-block {
55 display: inline-block;
56 width: 200px;
57 height: 100px;
58 background: yellow;
59 }
60</style>
61
62<span class="block">This span acts like a block</span>
63<div class="inline">This div</div> <div class="inline">acts inline</div>
64<div class="inline-block">Inline-block 1</div>
65<div class="inline-block">Inline-block 2</div>
12

What are HTML entities and when should you use them?

HTML entities are special codes used to display reserved characters, special symbols, or characters not on the keyboard. They start with & and end with ;. Common uses include: < (&lt;) and > (&gt;) for angle brackets, & (&amp;) for ampersand, " (&quot;) for quotes, © (&copy;) for copyright, and &nbsp; for non-breaking space. Use entities when you need to display HTML syntax as text, show special symbols, or prevent character encoding issues.

example.js
1<!-- Reserved characters -->
2<p>To display HTML tags, use entities:</p>
3<p>The &lt;div&gt; tag is a container element.</p>
4<!-- Displays: The <div> tag is a container element. -->
5
6<p>AT&amp;T is a company name</p>
7<!-- Displays: AT&T is a company name -->
8
9<p>She said &quot;Hello&quot;</p>
10<!-- Displays: She said "Hello" -->
11
12<!-- Special symbols -->
13<p>&copy; 2026 Company Name. All rights reserved.</p>
14<!-- Displays: © 2026 Company Name. All rights reserved. -->
15
16<p>Price: $100 &mdash; Save 20&percnt;</p>
17<!-- Displays: Price: $100 — Save 20% -->
18
19<p>Temperature: 72&deg;F</p>
20<!-- Displays: Temperature: 72°F -->
21
22<!-- Spacing entities -->
23<p>Multiple&nbsp;&nbsp;&nbsp;non-breaking&nbsp;spaces</p>
24<!-- Non-breaking spaces keep words together -->
25
26<p>Em&emsp;space&emsp;here</p>
27<!-- Wide space -->
28
29<p>En&ensp;space&ensp;here</p>
30<!-- Medium space -->
31
32<!-- Mathematical symbols -->
33<p>2 &times; 3 = 6</p>
34<!-- Displays: 2 × 3 = 6 -->
35
36<p>10 &divide; 2 = 5</p>
37<!-- Displays: 10 ÷ 2 = 5 -->
38
39<p>x &plusmn; 5</p>
40<!-- Displays: x ± 5 -->
41
42<!-- Common HTML entities -->
43<!--
44&lt; < less than
45&gt; > greater than
46&amp; & ampersand
47&quot; " quotation mark
48&apos; ' apostrophe
49&nbsp; non-breaking space
50&copy; © copyright
51&reg; ® registered trademark
52&trade; ™ trademark
53&euro; € euro
54&pound; £ pound
55&yen; ¥ yen
56&deg; ° degree
57&times; × multiplication
58&divide; ÷ division
59&ndash; – en dash
60&mdash; — em dash
61&hellip; … ellipsis
62&larr; ← left arrow
63&rarr; → right arrow
64&uarr; ↑ up arrow
65&darr; ↓ down arrow
66-->
67
68<!-- Numeric character references -->
69<p>&#60; is same as &lt;</p>
70<p>&#169; is same as &copy;</p>
13

What is the purpose of the alt attribute in images?

The alt attribute provides alternative text for images when they can't be displayed or viewed. It's crucial for accessibility - screen readers read alt text to visually impaired users. It also improves SEO as search engines use it to understand image content. Alt text displays if the image fails to load, and helps users on slow connections. Every <img> should have alt attribute. Use empty alt="" for decorative images. Write descriptive alt text that conveys the image's purpose and content.

example.js
1<!-- Good alt text examples -->
2
3<!-- Informative image -->
4<img
5 src="product.jpg"
6 alt="Red leather handbag with gold chain strap">
7
8<!-- Functional image (logo linking to home) -->
9<a href="/">
10 <img
11 src="logo.png"
12 alt="Company Name - Return to homepage">
13</a>
14
15<!-- Image of text -->
16<img
17 src="quote.jpg"
18 alt="Quote: The only way to do great work is to love what you do - Steve Jobs">
19
20<!-- Complex image (chart/graph) -->
21<img
22 src="sales-chart.png"
23 alt="Bar chart showing 50% increase in sales from Q1 to Q4 2025">
24
25<!-- Avatar/profile picture -->
26<img
27 src="avatar.jpg"
28 alt="John Doe's profile picture">
29
30<!-- Bad alt text examples -->
31
32<!-- ❌ Too generic -->
33<img src="product.jpg" alt="image">
34<img src="product.jpg" alt="photo">
35<img src="product.jpg" alt="picture">
36
37<!-- ❌ Redundant phrases -->
38<img src="product.jpg" alt="Image of a red handbag">
39<img src="product.jpg" alt="Picture showing a handbag">
40
41<!-- ❌ Filename as alt -->
42<img src="IMG_1234.jpg" alt="IMG_1234.jpg">
43
44<!-- Decorative images (empty alt) -->
45<img
46 src="decorative-line.png"
47 alt=""
48 role="presentation">
49<!-- Empty alt tells screen readers to skip -->
50
51<!-- Image with caption -->
52<figure>
53 <img
54 src="sunset.jpg"
55 alt="Orange and pink sunset over mountain range">
56 <figcaption>
57 Sunset at Rocky Mountain National Park, 2025
58 </figcaption>
59</figure>
60
61<!-- Image button -->
62<button>
63 <img
64 src="search-icon.png"
65 alt="Search">
66</button>
67
68<!-- Guidelines for writing alt text -->
69<!--
70✅ DO:
71- Be specific and concise
72- Describe the content and function
73- Keep it under 125 characters
74- Include important text in the image
75- Consider the context
76- Use empty alt for decorative images
77
78❌ DON'T:
79- Use "image of" or "picture of"
80- Include filename
81- Be overly verbose
82- Repeat nearby text
83- Leave it out entirely
84- Use it for layout/decoration (use CSS)
85-->
14

What are the different input types in HTML5?

HTML5 introduced many new input types beyond text and password. These include: email, url, tel (phone), number, range (slider), date, time, datetime-local, month, week, color, search, and file. Each type provides automatic validation, special keyboards on mobile devices, and better UX. For example, email validates format, number shows up/down arrows, date shows a date picker, and color shows a color picker. Always include appropriate type for better accessibility and user experience.

example.js
1<!-- Text-based inputs -->
2<label>Text: <input type="text" placeholder="Enter text"></label>
3<label>Email: <input type="email" placeholder="user@example.com"></label>
4<label>URL: <input type="url" placeholder="https://example.com"></label>
5<label>Tel: <input type="tel" placeholder="123-456-7890"></label>
6<label>Search: <input type="search" placeholder="Search..."></label>
7<label>Password: <input type="password"></label>
8
9<!-- Numeric inputs -->
10<label>Number:
11 <input type="number" min="0" max="100" step="1" value="50">
12</label>
13
14<label>Range (Slider):
15 <input type="range" min="0" max="100" value="50">
16</label>
17
18<!-- Date and time inputs -->
19<label>Date: <input type="date" value="2026-01-31"></label>
20<label>Time: <input type="time" value="14:30"></label>
21<label>Datetime-local: <input type="datetime-local"></label>
22<label>Month: <input type="month" value="2026-01"></label>
23<label>Week: <input type="week" value="2026-W05"></label>
24
25<!-- Other inputs -->
26<label>Color:
27 <input type="color" value="#3498db">
28</label>
29
30<label>File:
31 <input type="file" accept="image/*">
32</label>
33
34<label>File (Multiple):
35 <input type="file" multiple accept=".pdf,.doc,.docx">
36</label>
37
38<!-- Boolean inputs -->
39<label>
40 <input type="checkbox" checked>
41 Checkbox
42</label>
43
44<label>
45 <input type="radio" name="option" value="1" checked>
46 Radio Option 1
47</label>
48<label>
49 <input type="radio" name="option" value="2">
50 Radio Option 2
51</label>
52
53<!-- Button inputs -->
54<input type="submit" value="Submit Form">
55<input type="reset" value="Reset Form">
56<input type="button" value="Click Me">
57
58<!-- Hidden input (for form data not shown to user) -->
59<input type="hidden" name="user_id" value="12345">
60
61<!-- Comprehensive form example -->
62<form>
63 <fieldset>
64 <legend>User Information</legend>
65
66 <label>Name:
67 <input type="text" name="name" required>
68 </label>
69
70 <label>Email:
71 <input type="email" name="email" required>
72 </label>
73
74 <label>Phone:
75 <input type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
76 </label>
77
78 <label>Age:
79 <input type="number" name="age" min="18" max="100">
80 </label>
81
82 <label>Birth Date:
83 <input type="date" name="birthdate">
84 </label>
85
86 <label>Website:
87 <input type="url" name="website">
88 </label>
89
90 <label>Favorite Color:
91 <input type="color" name="color">
92 </label>
93
94 <label>Profile Picture:
95 <input type="file" name="avatar" accept="image/*">
96 </label>
97
98 <button type="submit">Submit</button>
99 </fieldset>
100</form>
101
102<!-- Mobile device benefits -->
103<!--
104- type="email" → Shows @ key on mobile keyboard
105- type="tel" → Shows numeric keypad
106- type="url" → Shows .com key
107- type="number" → Shows numeric keyboard
108- type="date" → Shows date picker
109- type="color" → Shows color picker
110-->
15

What is the difference between id and class attributes?

id must be unique on the page - only one element can have a specific id. class can be used on multiple elements and elements can have multiple classes. id has higher CSS specificity than class. id is used for unique elements (navigation, header) and JavaScript targeting. class is for styling groups of elements and reusable styles. Use class for styling, id for unique identification. Both are case-sensitive. Follow naming conventions: use hyphens or camelCase, start with letter.

example.js
1<!-- ID - Unique identifier -->
2<div id="header">
3 <h1>Website Title</h1>
4</div>
5
6<div id="main-content">
7 <article id="article-123">Content</article>
8</div>
9
10<!-- ❌ BAD: Duplicate IDs (invalid HTML) -->
11<div id="box">First box</div>
12<div id="box">Second box</div> <!-- WRONG! -->
13
14<!-- CLASS - Reusable styles -->
15<div class="card">Card 1</div>
16<div class="card">Card 2</div>
17<div class="card">Card 3</div>
18
19<!-- Multiple classes on one element -->
20<div class="card featured large">
21 Featured Card
22</div>
23
24<button class="btn btn-primary btn-large">
25 Click Me
26</button>
27
28<!-- Combining ID and class -->
29<nav id="main-nav" class="navigation sticky">
30 <a href="#" class="nav-link active">Home</a>
31 <a href="#" class="nav-link">About</a>
32 <a href="#" class="nav-link">Contact</a>
33</nav>
34
35<!-- CSS specificity -->
36<style>
37 /* ID selector - specificity: 100 */
38 #header {
39 background: blue;
40 }
41
42 /* Class selector - specificity: 10 */
43 .header {
44 background: red;
45 }
46
47 /* Element selector - specificity: 1 */
48 div {
49 background: green;
50 }
51
52 /* Multiple classes */
53 .card {
54 padding: 20px;
55 border: 1px solid #ccc;
56 }
57
58 .card.featured {
59 border-color: gold;
60 background: yellow;
61 }
62
63 .card.large {
64 padding: 40px;
65 font-size: 1.2em;
66 }
67</style>
68
69<!-- JavaScript usage -->
70<script>
71 // Get element by ID (returns single element)
72 const header = document.getElementById('header');
73 const article = document.querySelector('#article-123');
74
75 // Get elements by class (returns collection)
76 const cards = document.getElementsByClassName('card');
77 const navLinks = document.querySelectorAll('.nav-link');
78
79 // Modify classes
80 const element = document.querySelector('.card');
81 element.classList.add('active');
82 element.classList.remove('featured');
83 element.classList.toggle('selected');
84 element.classList.contains('large'); // true/false
85
86 // Best practices for IDs in JavaScript
87 document.getElementById('submit-btn').addEventListener('click', () => {
88 console.log('Button clicked');
89 });
90</script>
91
92<!-- When to use ID vs Class -->
93<!--
94Use ID for:
95✅ Unique elements (header, footer, main navigation)
96✅ JavaScript targeting (form elements, buttons)
97✅ Fragment identifiers (anchor links: #section1)
98✅ Form label associations
99✅ ARIA landmark roles
100
101Use Class for:
102✅ Styling groups of elements
103✅ Reusable components
104✅ Multiple styling variations
105✅ CSS frameworks (Bootstrap, Tailwind)
106✅ Responsive design
107-->
108
109<!-- Naming conventions -->
110<!--
111✅ Good names:
112- IDs: header, main-nav, user-profile, submitBtn
113- Classes: btn, card, nav-link, text-center
114
115❌ Bad names:
116- IDs: div1, box, element
117- Classes: red, big, style1
118-->
16

What is the purpose of ARIA (Accessible Rich Internet Applications)?

ARIA provides additional semantics and attributes to make web content more accessible to people with disabilities, especially those using assistive technologies like screen readers. ARIA includes roles (define element purpose), properties (describe characteristics), and states (describe current condition). Common attributes include aria-label, aria-labelledby, aria-describedby, aria-hidden, role. Use ARIA when native HTML semantics aren't sufficient. Follow the rule: use semantic HTML first, ARIA only when necessary.

example.js
1<!-- ARIA Roles -->
2<div role="navigation">
3 <ul>
4 <li><a href="/">Home</a></li>
5 <li><a href="/about">About</a></li>
6 </ul>
7</div>
8<!-- Better: Use semantic <nav> element -->
9<nav>
10 <ul>
11 <li><a href="/">Home</a></li>
12 <li><a href="/about">About</a></li>
13 </ul>
14</nav>
15
16<!-- ARIA Labels -->
17<button aria-label="Close dialog">
18 <span aria-hidden="true">&times;</span>
19</button>
20
21<input
22 type="search"
23 aria-label="Search articles"
24 placeholder="Search...">
25
26<!-- aria-labelledby (reference to label element) -->
27<h2 id="dialog-title">Confirm Delete</h2>
28<div role="dialog" aria-labelledby="dialog-title">
29 <p>Are you sure you want to delete this item?</p>
30 <button>Delete</button>
31 <button>Cancel</button>
32</div>
33
34<!-- aria-describedby (additional description) -->
35<label for="password">Password</label>
36<input
37 type="password"
38 id="password"
39 aria-describedby="password-requirements">
40<span id="password-requirements">
41 Must be at least 8 characters with one number
42</span>
43
44<!-- ARIA States -->
45<button
46 aria-pressed="false"
47 aria-label="Toggle notifications">
48 Notifications
49</button>
50
51<div
52 role="alert"
53 aria-live="polite">
54 Form submitted successfully!
55</div>
56
57<!-- aria-expanded (for collapsible content) -->
58<button
59 aria-expanded="false"
60 aria-controls="menu">
61 Menu
62</button>
63<nav id="menu" hidden>
64 <!-- Menu items -->
65</nav>
66
67<!-- aria-hidden (hide from screen readers) -->
68<span aria-hidden="true" class="icon"></span>
69<span class="sr-only">Favorite</span>
70
71<!-- ARIA in forms -->
72<form>
73 <div role="group" aria-labelledby="contact-heading">
74 <h3 id="contact-heading">Contact Information</h3>
75
76 <label for="email">Email</label>
77 <input
78 type="email"
79 id="email"
80 aria-required="true"
81 aria-invalid="false"
82 aria-describedby="email-error">
83 <span id="email-error" role="alert" hidden>
84 Please enter a valid email
85 </span>
86 </div>
87</form>
88
89<!-- ARIA Live Regions (dynamic content) -->
90<div
91 role="status"
92 aria-live="polite"
93 aria-atomic="true">
94 Loading...
95</div>
96
97<div
98 role="alert"
99 aria-live="assertive">
100 Error: Connection lost!
101</div>
102
103<!-- Common ARIA roles -->
104<!--
105Landmark roles:
106- role="banner" → <header>
107- role="navigation" → <nav>
108- role="main" → <main>
109- role="complementary" → <aside>
110- role="contentinfo" → <footer>
111- role="search" → <form role="search">
112
113Widget roles:
114- role="button" → <button>
115- role="checkbox" → <input type="checkbox">
116- role="dialog" → modal dialogs
117- role="tab" / role="tabpanel" → tabs
118- role="menu" / role="menuitem" → menus
119- role="progressbar" → progress indicators
120- role="slider" → range inputs
121- role="alert" → important messages
122
123Document roles:
124- role="article" → <article>
125- role="list" → <ul> or <ol>
126- role="listitem" → <li>
127-->
128
129<!-- Best practices -->
130<!--
131✅ DO:
132- Use semantic HTML first
133- Test with screen readers
134- Provide text alternatives
135- Use ARIA labels for icon buttons
136- Keep live regions updated
137
138❌ DON'T:
139- Use ARIA when HTML suffices
140- Use role="presentation" on focusable elements
141- Create keyboard traps
142- Rely only on color for meaning
143- Forget to test accessibility
144-->
145
146<!-- Keyboard navigation -->
147<div role="tablist" aria-label="Content tabs">
148 <button
149 role="tab"
150 aria-selected="true"
151 aria-controls="panel-1"
152 tabindex="0">
153 Tab 1
154 </button>
155 <button
156 role="tab"
157 aria-selected="false"
158 aria-controls="panel-2"
159 tabindex="-1">
160 Tab 2
161 </button>
162</div>
163
164<div id="panel-1" role="tabpanel" aria-labelledby="tab-1">
165 Content for tab 1
166</div>
167<div id="panel-2" role="tabpanel" aria-labelledby="tab-2" hidden>
168 Content for tab 2
169</div>
17

What are SVG and Canvas? When would you use each?

SVG (Scalable Vector Graphics) is XML-based vector graphics that scale without quality loss. Canvas is a bitmap drawing API using JavaScript. SVG is DOM-based (elements can be styled/animated with CSS), canvas is pixel-based (drawn with JavaScript). Use SVG for: logos, icons, charts, interactive graphics, accessibility. Use Canvas for: games, image manipulation, real-time rendering, particle effects, when dealing with thousands of objects. SVG is better for static/interactive graphics, Canvas for dynamic/performance-critical rendering.

example.js
1<!-- SVG (Scalable Vector Graphics) -->
2<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
3 <!-- Circle -->
4 <circle
5 cx="100"
6 cy="100"
7 r="50"
8 fill="blue"
9 stroke="red"
10 stroke-width="3" />
11
12 <!-- Rectangle -->
13 <rect
14 x="20"
15 y="20"
16 width="60"
17 height="40"
18 fill="green" />
19
20 <!-- Line -->
21 <line
22 x1="0"
23 y1="0"
24 x2="200"
25 y2="200"
26 stroke="black"
27 stroke-width="2" />
28
29 <!-- Text -->
30 <text
31 x="100"
32 y="180"
33 text-anchor="middle"
34 fill="purple"
35 font-size="20">
36 SVG Text
37 </text>
38
39 <!-- Path (complex shapes) -->
40 <path
41 d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30"
42 stroke="orange"
43 fill="none"
44 stroke-width="2" />
45</svg>
46
47<!-- SVG with CSS animation -->
48<svg width="100" height="100">
49 <circle
50 class="animated-circle"
51 cx="50"
52 cy="50"
53 r="40"
54 fill="red" />
55</svg>
56
57<style>
58 .animated-circle {
59 animation: pulse 2s infinite;
60 }
61
62 @keyframes pulse {
63 0%, 100% { r: 40; }
64 50% { r: 45; }
65 }
66
67 /* SVG is fully stylable with CSS */
68 svg circle:hover {
69 fill: blue;
70 cursor: pointer;
71 }
72</style>
73
74<!-- SVG icons (inline) -->
75<button>
76 <svg width="20" height="20" viewBox="0 0 24 24">
77 <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
78 </svg>
79 Menu
80</button>
81
82<!-- Canvas -->
83<canvas id="myCanvas" width="400" height="400"></canvas>
84
85<script>
86 const canvas = document.getElementById('myCanvas');
87 const ctx = canvas.getContext('2d');
88
89 // Draw rectangle
90 ctx.fillStyle = 'blue';
91 ctx.fillRect(50, 50, 100, 80);
92
93 // Draw circle
94 ctx.beginPath();
95 ctx.arc(200, 200, 50, 0, Math.PI * 2);
96 ctx.fillStyle = 'red';
97 ctx.fill();
98 ctx.strokeStyle = 'black';
99 ctx.lineWidth = 3;
100 ctx.stroke();
101
102 // Draw line
103 ctx.beginPath();
104 ctx.moveTo(0, 0);
105 ctx.lineTo(400, 400);
106 ctx.strokeStyle = 'green';
107 ctx.lineWidth = 2;
108 ctx.stroke();
109
110 // Draw text
111 ctx.font = '30px Arial';
112 ctx.fillStyle = 'purple';
113 ctx.fillText('Canvas Text', 100, 350);
114
115 // Animation example
116 let x = 0;
117 function animate() {
118 ctx.clearRect(0, 0, canvas.width, canvas.height);
119 ctx.fillStyle = 'orange';
120 ctx.fillRect(x, 100, 50, 50);
121 x += 2;
122 if (x > canvas.width) x = 0;
123 requestAnimationFrame(animate);
124 }
125 animate();
126</script>
127
128<!-- When to use SVG vs Canvas -->
129<!--
130Use SVG when:
131✅ Graphics need to scale (logos, icons)
132✅ Need accessibility (screen readers)
133✅ Want CSS/DOM manipulation
134✅ Creating charts/graphs
135✅ Interactive graphics (click, hover)
136✅ Few objects (< 10,000)
137✅ Vector graphics are needed
138✅ SEO matters (text in SVG is indexable)
139
140Use Canvas when:
141✅ Drawing games
142✅ Real-time rendering
143✅ Image manipulation/filters
144✅ Particle effects
145✅ Many objects (> 10,000)
146✅ Pixel-level control needed
147✅ Better performance for complex scenes
148✅ Creating videos/animations
149-->
150
151<!-- SVG vs Canvas comparison -->
152<!--
153SVG:
154- Vector-based (infinite zoom)
155- DOM elements (inspectable)
156- Event handlers per element
157- Resolution independent
158- Slower with many elements
159- Good for static/interactive graphics
160- Accessible by default
161- Larger file size for complex graphics
162
163Canvas:
164- Pixel-based (fixed resolution)
165- Single element (not inspectable)
166- Manual event handling
167- Resolution dependent
168- Faster with many elements
169- Good for dynamic rendering
170- Not accessible without extra work
171- Smaller memory footprint
172-->
18

What is the purpose of the viewport meta tag?

The viewport meta tag controls how a webpage is displayed on mobile devices. It sets the visible area of the page and controls zoom behavior. Without it, mobile browsers render pages at desktop width (usually 980px) and scale down, making content tiny. The tag <meta name='viewport' content='width=device-width, initial-scale=1.0'> makes the page responsive by setting width to device width and preventing zoom on rotation. Essential for responsive design and mobile-first development.

example.js
1<!-- Essential viewport meta tag (most common) -->
2<head>
3 <meta
4 name="viewport"
5 content="width=device-width, initial-scale=1.0">
6</head>
7
8<!-- Viewport properties explained -->
9<!--
10width=device-width
11- Sets viewport width to device screen width
12- Without this, mobile shows desktop layout scaled down
13
14initial-scale=1.0
15- Sets initial zoom level (1.0 = 100%, no zoom)
16- Prevents auto-zoom on page load
17
18maximum-scale=5.0
19- Sets maximum zoom level
20- Default is 5.0 (500%)
21
22minimum-scale=0.25
23- Sets minimum zoom level
24- Default is 0.25 (25%)
25
26user-scalable=yes
27- Allows user to zoom in/out
28- Default is yes
29- IMPORTANT: Never use user-scalable=no (accessibility issue)
30-->
31
32<!-- Different viewport configurations -->
33
34<!-- Standard responsive (recommended) -->
35<meta
36 name="viewport"
37 content="width=device-width, initial-scale=1.0">
38
39<!-- With zoom limits -->
40<meta
41 name="viewport"
42 content="width=device-width, initial-scale=1.0, maximum-scale=5.0, minimum-scale=1.0">
43
44<!-- ❌ BAD: Disabling zoom (accessibility issue) -->
45<meta
46 name="viewport"
47 content="width=device-width, initial-scale=1.0, user-scalable=no">
48<!-- DON'T DO THIS - prevents accessibility for vision-impaired users -->
49
50<!-- Fixed width (not responsive) -->
51<meta
52 name="viewport"
53 content="width=1024">
54
55<!-- Without viewport meta tag -->
56<!--
57Mobile browsers:
58- Render at ~980px width
59- Scale down to fit screen
60- Text becomes tiny
61- User must zoom/pan
62- Poor mobile experience
63-->
64
65<!-- With viewport meta tag -->
66<!--
67Mobile browsers:
68- Render at device width (e.g., 375px for iPhone)
69- Text readable without zoom
70- Proper responsive layout
71- Good mobile experience
72-->
73
74<!-- Complete responsive page example -->
75<!DOCTYPE html>
76<html lang="en">
77<head>
78 <meta charset="UTF-8">
79 <meta name="viewport" content="width=device-width, initial-scale=1.0">
80 <title>Responsive Page</title>
81 <style>
82 /* Mobile-first CSS */
83 body {
84 font-size: 16px;
85 padding: 20px;
86 }
87
88 .container {
89 max-width: 1200px;
90 margin: 0 auto;
91 }
92
93 /* Tablet */
94 @media (min-width: 768px) {
95 body {
96 font-size: 18px;
97 }
98 }
99
100 /* Desktop */
101 @media (min-width: 1024px) {
102 body {
103 font-size: 20px;
104 }
105 }
106 </style>
107</head>
108<body>
109 <div class="container">
110 <h1>Responsive Page</h1>
111 <p>This page adapts to different screen sizes.</p>
112 </div>
113</body>
114</html>
115
116<!-- iOS-specific viewport -->
117<meta
118 name="viewport"
119 content="width=device-width, initial-scale=1.0, viewport-fit=cover">
120<!-- viewport-fit=cover for devices with notch (iPhone X+) -->
121
122<!-- Other related meta tags -->
123<meta name="apple-mobile-web-app-capable" content="yes">
124<meta name="mobile-web-app-capable" content="yes">
125<meta name="theme-color" content="#3498db">
126
127<!-- Common mistakes -->
128<!--
129❌ Forgetting viewport tag entirely
130❌ Using user-scalable=no
131❌ Setting fixed width instead of device-width
132❌ Using maximum-scale=1.0 (prevents zoom)
133❌ Not testing on real devices
134-->
19

What is the difference between localStorage, sessionStorage, and cookies?

All three store data client-side but differ in scope and lifetime. localStorage persists until explicitly deleted, stores 5-10MB, accessible only via JavaScript, same-origin only. sessionStorage clears when tab/window closes, stores 5-10MB, per-tab isolation, JavaScript only. Cookies expire based on set date, store 4KB, sent with every HTTP request, accessible by server and JavaScript. Use localStorage for app preferences, sessionStorage for temporary data, cookies for authentication/session management requiring server access.

example.js
1<!-- localStorage - Persistent storage -->
2<script>
3 // Store data (persists after browser close)
4 localStorage.setItem('username', 'JohnDoe');
5 localStorage.setItem('theme', 'dark');
6 localStorage.setItem('settings', JSON.stringify({
7 notifications: true,
8 language: 'en'
9 }));
10
11 // Retrieve data
12 const username = localStorage.getItem('username');
13 console.log(username); // "JohnDoe"
14
15 const settings = JSON.parse(localStorage.getItem('settings'));
16 console.log(settings.notifications); // true
17
18 // Remove specific item
19 localStorage.removeItem('theme');
20
21 // Clear all localStorage
22 localStorage.clear();
23
24 // Check if key exists
25 if (localStorage.getItem('username')) {
26 console.log('User is logged in');
27 }
28
29 // Storage size
30 console.log(localStorage.length); // Number of items
31
32 // Iterate through all items
33 for (let i = 0; i < localStorage.length; i++) {
34 const key = localStorage.key(i);
35 const value = localStorage.getItem(key);
36 console.log(`${key}: ${value}`);
37 }
38</script>
39
40<!-- sessionStorage - Tab-scoped storage -->
41<script>
42 // Store data (clears when tab closes)
43 sessionStorage.setItem('currentPage', '1');
44 sessionStorage.setItem('searchQuery', 'javascript');
45
46 // Retrieve data
47 const page = sessionStorage.getItem('currentPage');
48
49 // Same API as localStorage
50 sessionStorage.removeItem('searchQuery');
51 sessionStorage.clear();
52
53 // Use case: Multi-step form
54 function saveFormProgress() {
55 const formData = {
56 step: 2,
57 email: 'user@example.com',
58 preferences: ['newsletter', 'updates']
59 };
60 sessionStorage.setItem('formProgress', JSON.stringify(formData));
61 }
62
63 function loadFormProgress() {
64 const saved = sessionStorage.getItem('formProgress');
65 return saved ? JSON.parse(saved) : null;
66 }
67</script>
68
69<!-- Cookies - Server-accessible storage -->
70<script>
71 // Set cookie (expires in 7 days)
72 function setCookie(name, value, days) {
73 const date = new Date();
74 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
75 const expires = "expires=" + date.toUTCString();
76 document.cookie = `${name}=${value};${expires};path=/`;
77 }
78
79 setCookie('sessionId', 'abc123', 7);
80 setCookie('userRole', 'admin', 30);
81
82 // Get cookie
83 function getCookie(name) {
84 const nameEQ = name + "=";
85 const cookies = document.cookie.split(';');
86 for (let cookie of cookies) {
87 cookie = cookie.trim();
88 if (cookie.indexOf(nameEQ) === 0) {
89 return cookie.substring(nameEQ.length);
90 }
91 }
92 return null;
93 }
94
95 const sessionId = getCookie('sessionId');
96 console.log(sessionId); // "abc123"
97
98 // Delete cookie (set expiry to past)
99 function deleteCookie(name) {
100 document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
101 }
102
103 deleteCookie('sessionId');
104
105 // Cookie with options
106 document.cookie = "token=xyz789; expires=Fri, 31 Dec 2026 23:59:59 UTC; path=/; secure; samesite=strict";
107
108 // Cookie options:
109 // secure - Only sent over HTTPS
110 // httpOnly - Not accessible via JavaScript (set server-side only)
111 // samesite - CSRF protection (strict, lax, none)
112 // domain - Cookie domain
113 // path - Cookie path
114</script>
115
116<!-- Comparison table -->
117<!--
118Feature | localStorage | sessionStorage | Cookies
119-----------------+---------------+----------------+--------------
120Capacity | ~5-10MB | ~5-10MB | ~4KB
121Expiration | Never | Tab close | Set by user
122Scope | Same origin | Same tab | Same origin
123Sent to server | No | No | Yes
124Accessibility | JavaScript | JavaScript | Both
125Storage location | Browser | Browser | Browser
126Persistence | Permanent | Temporary | Until expiry
127Use case | App settings | Temp data | Auth/Session
128-->
129
130<!-- Use cases -->
131<!--
132localStorage:
133✅ User preferences (theme, language)
134✅ Shopping cart
135✅ Cached data
136✅ App state
137✅ Form autosave
138✅ Offline functionality
139
140sessionStorage:
141✅ Multi-step form data
142✅ Temporary filters/sorting
143✅ One-time messages
144✅ Tab-specific state
145✅ Wizard progress
146✅ Current page state
147
148Cookies:
149✅ Authentication tokens
150✅ Session management
151✅ Tracking/analytics
152✅ Personalization
153✅ CSRF tokens
154✅ Server communication
155-->
156
157<!-- Storage event (localStorage/sessionStorage) -->
158<script>
159 // Listen for storage changes in other tabs
160 window.addEventListener('storage', (e) => {
161 console.log('Storage changed:');
162 console.log('Key:', e.key);
163 console.log('Old value:', e.oldValue);
164 console.log('New value:', e.newValue);
165 console.log('URL:', e.url);
166 console.log('Storage area:', e.storageArea);
167 });
168
169 // Note: storage event only fires in OTHER tabs/windows
170 // Not in the tab that made the change
171</script>
172
173<!-- Best practices -->
174<!--
175✅ DO:
176- Always check for storage availability
177- Store only necessary data
178- Use JSON.stringify/parse for objects
179- Set appropriate expiration for cookies
180- Use secure, httpOnly, samesite for sensitive cookies
181- Clean up old data periodically
182- Handle QuotaExceededError
183
184❌ DON'T:
185- Store sensitive data (passwords, credit cards)
186- Store large files
187- Assume storage is available
188- Store data without user consent (GDPR)
189- Use cookies for large data
190- Forget to parse JSON when retrieving
191-->
20

What is lazy loading and how do you implement it in HTML?

Lazy loading defers loading of non-critical resources (images, iframes) until they're needed, improving initial page load time and saving bandwidth. HTML native lazy loading uses the loading='lazy' attribute on <img> and <iframe>. Browsers automatically load images/iframes only when they're about to enter the viewport. Benefits include faster initial load, reduced data usage, better performance scores. Use loading='eager' for above-the-fold content, loading='lazy' for below-the-fold. Supported in all modern browsers.

example.js
1<!-- Native lazy loading for images -->
2<img
3 src="image.jpg"
4 alt="Description"
5 loading="lazy"
6 width="800"
7 height="600">
8<!-- Browser loads image when near viewport -->
9
10<!-- Above-the-fold images (load immediately) -->
11<img
12 src="hero-image.jpg"
13 alt="Hero banner"
14 loading="eager"
15 width="1920"
16 height="1080">
17<!-- Important: First 1-2 images should use eager -->
18
19<!-- Lazy loading for iframes -->
20<iframe
21 src="https://www.youtube.com/embed/video-id"
22 loading="lazy"
23 width="560"
24 height="315"
25 title="Video title">
26</iframe>
27
28<!-- Multiple images with lazy loading -->
29<div class="gallery">
30 <img src="photo1.jpg" alt="Photo 1" loading="lazy" width="400" height="300">
31 <img src="photo2.jpg" alt="Photo 2" loading="lazy" width="400" height="300">
32 <img src="photo3.jpg" alt="Photo 3" loading="lazy" width="400" height="300">
33 <img src="photo4.jpg" alt="Photo 4" loading="lazy" width="400" height="300">
34 <img src="photo5.jpg" alt="Photo 5" loading="lazy" width="400" height="300">
35</div>
36
37<!-- Best practice: Always specify dimensions -->
38<img
39 src="product.jpg"
40 alt="Product name"
41 loading="lazy"
42 width="600"
43 height="400"
44 style="max-width: 100%; height: auto;">
45<!-- Prevents layout shift when image loads -->
46
47<!-- Responsive images with lazy loading -->
48<img
49 srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
50 sizes="(max-width: 600px) 400px, (max-width: 900px) 800px, 1200px"
51 src="medium.jpg"
52 alt="Responsive image"
53 loading="lazy"
54 width="1200"
55 height="800">
56
57<!-- Picture element with lazy loading -->
58<picture>
59 <source
60 media="(min-width: 800px)"
61 srcset="large.jpg"
62 width="1200"
63 height="800">
64 <source
65 media="(min-width: 400px)"
66 srcset="medium.jpg"
67 width="800"
68 height="600">
69 <img
70 src="small.jpg"
71 alt="Responsive picture"
72 loading="lazy"
73 width="400"
74 height="300">
75</picture>
76
77<!-- Loading attribute values -->
78<!--
79loading="lazy"
80- Defers loading until near viewport
81- Use for below-the-fold images/iframes
82- Default distance: ~3000px from viewport
83
84loading="eager"
85- Loads immediately (default behavior)
86- Use for above-the-fold content
87- First hero image, logo, etc.
88
89loading="auto"
90- Browser decides (default if not specified)
91-->
92
93<!-- JavaScript fallback for older browsers -->
94<script>
95 // Check for native lazy loading support
96 if ('loading' in HTMLImageElement.prototype) {
97 // Browser supports native lazy loading
98 console.log('Native lazy loading supported');
99 } else {
100 // Fallback: Use Intersection Observer or library
101 console.log('Native lazy loading not supported');
102
103 // Load polyfill or use custom implementation
104 const images = document.querySelectorAll('img[loading="lazy"]');
105
106 const imageObserver = new IntersectionObserver((entries, observer) => {
107 entries.forEach(entry => {
108 if (entry.isIntersecting) {
109 const img = entry.target;
110 img.src = img.dataset.src;
111 img.classList.remove('lazy');
112 observer.unobserve(img);
113 }
114 });
115 });
116
117 images.forEach(img => imageObserver.observe(img));
118 }
119</script>
120
121<!-- Advanced: Intersection Observer implementation -->
122<img
123 data-src="image.jpg"
124 alt="Lazy image"
125 class="lazy"
126 width="800"
127 height="600">
128
129<script>
130 document.addEventListener('DOMContentLoaded', () => {
131 const lazyImages = document.querySelectorAll('img.lazy');
132
133 const imageObserver = new IntersectionObserver((entries, observer) => {
134 entries.forEach(entry => {
135 if (entry.isIntersecting) {
136 const img = entry.target;
137 img.src = img.dataset.src;
138 img.classList.remove('lazy');
139 img.classList.add('loaded');
140 observer.unobserve(img);
141 }
142 });
143 }, {
144 rootMargin: '50px' // Start loading 50px before entering viewport
145 });
146
147 lazyImages.forEach(img => imageObserver.observe(img));
148 });
149</script>
150
151<!-- Placeholder while loading -->
152<img
153 src="placeholder.jpg"
154 data-src="full-image.jpg"
155 alt="Image"
156 loading="lazy"
157 class="lazy"
158 style="background: #f0f0f0;">
159<!-- Low-res placeholder loads first -->
160
161<!-- Best practices -->
162<!--
163✅ DO:
164- Use loading="lazy" for below-the-fold images
165- Use loading="eager" for above-the-fold images
166- Always specify width and height
167- Use appropriate placeholders
168- Test on slow connections
169- Consider Cumulative Layout Shift (CLS)
170- Use for images and iframes
171
172❌ DON'T:
173- Lazy load above-the-fold content
174- Forget width/height (causes layout shift)
175- Lazy load all images (first 1-2 should be eager)
176- Use without testing performance
177- Rely only on lazy loading for performance
178- Ignore browser support
179-->
180
181<!-- Performance benefits -->
182<!--
183✅ Faster initial page load
184✅ Reduced bandwidth usage
185✅ Better Largest Contentful Paint (LCP)
186✅ Improved Time to Interactive (TTI)
187✅ Lower data costs for users
188✅ Better mobile experience
189✅ Higher lighthouse scores
190-->

Ready for More Interview Prep?

Explore our complete collection of frontend interview questions covering CSS, JavaScript, React, and more.

View All Topics

© 2026 GyaanSetu. Helping developers ace their interviews.