HTML Interview Questions & Answers
Crack frontend interviews with 50+ top HTML questions, from basics to advanced.
Basic HTML Interview Questions
What is HTML?
Answer:
HTML (HyperText Markup Language) is the standard markup language for creating web pages.
What are HTML tags?
Answer:
HTML tags are the hidden keywords within a web page that define how the browser must format and display the content.
What is the basic structure of an HTML document?
Answer:
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <!-- Content goes here --> </body> </html>
What is the DOCTYPE declaration?
Answer:
The DOCTYPE declaration specifies the HTML version and helps browsers to render the page correctly.
What are HTML attributes?
Answer:
Attributes provide additional information about HTML elements and are always specified in the start tag.
What is the difference between HTML elements and tags?
Answer:
An HTML element consists of a start tag, content, and end tag. A tag is just the opening or closing marker (like <p> or </p>).
What are void elements in HTML?
Answer:
Void elements don't have closing tags or content, like <br>, <img>, <input>, <hr>, etc.
What is the difference between <strong> and <b> tags?
Answer:
<strong> indicates importance and typically renders as bold, while <b> is just for styling text as bold without semantic meaning.
What is the difference between <em> and <i> tags?
Answer:
<em> indicates emphasis and typically renders as italic, while <i> is just for styling text as italic without semantic meaning.
What is semantic HTML?
Answer:
Semantic HTML uses elements that clearly describe their meaning to both browser and developer (like <header>, <footer>, <article>).
What are some semantic HTML5 elements?
Answer:
<header>, <footer>, <nav>, <article>, <section>, <aside>, <main>, <figure>, <figcaption>, <time>, <mark>
What is the purpose of the <head> element?
Answer:
The <head> element contains meta-information about the document like title, styles, scripts, and character set declarations.
What is the purpose of the <meta> tag?
Answer:
<meta> tags provide metadata about the HTML document, like character set, viewport settings, author, description, and keywords.
What is the viewport meta tag?
Answer:
<meta name="viewport" content="width=device-width, initial-scale=1.0"> - It controls layout on mobile browsers.
What are HTML comments?
Answer:
HTML comments are written as <!-- comment --> and are ignored by the browser.
What is the difference between <ul> and <ol>?
Answer:
<ul> creates an unordered (bulleted) list, while <ol> creates an ordered (numbered) list.
Example:
The fundamental difference lies in semantic meaning and default visual presentation.
<ul> (Unordered List):
- Semantic Meaning: Order of items does not matter.
- Default Visual Presentation: Bullet points.
- Example Use: Shopping list, product features.
<ol> (Ordered List):
- Semantic Meaning: Order of items is significant.
- Default Visual Presentation: Numbers, letters, or Roman numerals.
- Example Use: Recipe steps, ranked lists.
The choice depends on whether the sequence of items is important to the content's meaning.What is the <dl> element used for?
Answer:
<dl> defines a description list, with <dt> for terms and <dd> for descriptions.
How to create a hyperlink in HTML?
Answer:
<a href="url">link text</a> - The href attribute specifies the destination.
Example:
<a href="url">link text</a>What is the purpose of the alt attribute in images?
Answer:
The alt attribute provides alternative text for images if they cannot be displayed, and is important for accessibility and SEO.
How to embed an image in HTML?
Answer:
The src attribute specifies the image path.
Example:
<img src="image.jpg" alt="description">What is the difference between absolute and relative URLs?
Answer:
Absolute URLs contain the full path (https://example.com/page.html), while relative URLs specify paths relative to the current page (images/pic.jpg).
How to create a table in HTML?
Answer:
Here is the syntax
Example:
<table>
<tr>
<th>Header</th>
<th>Header</th>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
</tr>
</table>What are the differences between <th> and <td>?
Answer:
<th> defines a header cell in a table (bold and centered by default), while <td> defines a standard data cell.
What is the colspan attribute?
Answer:
colspan specifies how many columns a table cell should span horizontally.
Example:
<table border="1">
<tr>
<th>Header 1</th>
<th colspan="2">Header 2 & 3 (spans 2 columns)</th>
</tr>
<tr>
<td>Data A</td>
<td>Data B</td>
<td>Data C</td>
</tr>
<tr>
<td>Data D</td>
<td colspan="2">Data E & F (spans 2 columns)</td>
</tr>
</table>What is the rowspan attribute?
Answer:
rowspan specifies how many rows a table cell should span vertically.
Example:
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td rowspan="2">Data A (spans 2 rows)</td>
<td>Data B</td>
<td>Data C</td>
</tr>
<tr>
<td>Data D</td>
<td>Data E</td>
</tr>
</table>How to create a form in HTML?
Answer:
Here's the structure:
Example:
<form action="/submit-data" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="user_name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="user_email"><br><br>
<input type="submit" value="Submit">
</form>What are common form input types?
Answer:
text, password, email, number, date, checkbox, radio, file, submit, button, hidden, range, color, etc.
What is the difference between GET and POST methods?
Answer:
GET appends data to URL with length limits, while POST sends data in the request body without URL exposure and has no size limits.
What is the purpose of the name attribute in form elements?
Answer:
The name attribute identifies form data when it's submitted to the server.
What is the <label> element used for?
Answer:
<label> improves accessibility by associating text with form controls, and increases clickable area for checkboxes/radio buttons.
Example:
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="checkbox" id="newsletter" name="newsletter">
<label for="newsletter">Sign up for our newsletter</label>What is the <fieldset> element?
Answer:
<fieldset> groups related form elements together, often with a <legend> as caption.
Example:
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName"><br><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName">
</fieldset>
<fieldset>
<legend>Contact Details</legend>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone">
</fieldset>
<button type="submit">Submit</button>
</form>What is the <textarea> element?
Answer:
<textarea> creates a multi-line text input control with rows and cols attributes to specify size.
Example:
<label for="myMessage">Your Message:</label>
<textarea id="myMessage" name="userMessage" rows="5" cols="30">
This is some default text that can be edited.
</textarea>What is the <select> element?
Answer:
<select> creates a drop-down list with <option> elements for each item.
Example:
<select id="fruits" name="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
<option value="grape">Grape</option>
</select>How to create radio buttons?
Answer:
Here's the structure:
Example:
<input type="radio" name="group" value="1"> Option 1
<input type="radio" name="group" value="2"> Option 2
(Note: Same name groups them for single selection)What is the difference between <iframe>, <embed>, and <object>?
Answer:
All embed external content, but <iframe> is for web pages, <embed> is for plugins, and <object> is more versatile but complex.
What are data attributes?
Answer:
Custom attributes prefixed with 'data-' (like data-id) used to store extra information without affecting presentation.
What is the purpose of the <canvas> element?
Answer:
<canvas> is used to draw graphics via JavaScript, useful for games, visualizations, and animations.
What is the purpose of the <svg> element?
Answer:
<svg> defines vector-based graphics in XML format that can scale without losing quality.
What is the difference between localStorage and sessionStorage?
Answer:
localStorage persists until manually cleared, while sessionStorage lasts only for the browser session.
What are HTML entities?
Answer:
Special codes for reserved/special characters like < (<), > (>), & (&), © (©).
What is the purpose of the <audio> element?
Answer:
<audio> embeds sound content with support for multiple sources via <source> elements.
Example:
<audio src="song.mp3" controls>
Your browser does not support the audio element.
</audio>What is the purpose of the <video> element?
Answer:
<video> embeds video content with support for multiple sources via <source> elements.
Example:
Basic Usage:
<video src="movie.mp4" controls width="640" height="360">
Your browser does not support the video tag.
</video>
Using Multiple Sources (for Browser Compatibility):
<video controls width="640" height="360" poster="poster.jpg">
<source src="movie.mp4" type="video/mp4">
<source src="movie.webm" type="video/webm">
<p>Your browser does not support HTML video. Here is a <a href="movie.mp4">link to the video</a> instead.</p>
</video>What is the difference between <figure> and <img>?
Answer:
<figure> is a semantic container for images, diagrams, etc. that can include a <figcaption>, while <img> just embeds an image.
What is the purpose of the <progress> element?
Answer:
<progress> displays a progress bar representing completion of a task.
Example:
<label for="download-progress">Downloading file:</label>
<progress id="download-progress" value="50" max="100"> 50% </progress>What is the purpose of the <meter> element?
Answer:
<meter> represents a scalar measurement within a known range (like disk usage).
Example:
<label for="disk_usage">Disk usage:</label>
<meter id="disk_usage" value="0.6">60%</meter>What is the purpose of the <datalist> element?
Answer:
<datalist> provides autocomplete options for <input> elements via the list attribute.
Example:
<label for="browser">Choose your favorite browser:</label>
<input list="browsers" id="browser" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
<option value="Opera">
</datalist>What is the purpose of the <output> element?
Answer:
<output> represents the result of a calculation or user action.
Example:
<form oninput="result.value = parseInt(a.value) + parseInt(b.value)">
<label for="a">Value A:</label>
<input type="number" id="a" value="10"> +
<label for="b">Value B:</label>
<input type="number" id="b" value="20"> =
<output name="result" for="a b"></output>
</form>What is the purpose of the <template> element?
Answer:
<template> holds HTML content that won't be rendered immediately but can be used later with JavaScript.
Example:
<button id="add-item-btn">Add New Item</button>
<ul id="item-list">
<li>Existing Item 1</li>
</ul>
<template id="new-item-template">
<li>New Item! <button class="delete-btn">X</button></li>
</template>
<script>
document.getElementById('add-item-btn').addEventListener('click', function() {
const template = document.getElementById('new-item-template');
const clone = template.content.cloneNode(true); // Clone the template's content
document.getElementById('item-list').appendChild(clone);
});
</script>What is the purpose of the <details> and <summary> elements?
Answer:
They create a disclosure widget where <summary> provides the visible heading and <details> contains the collapsible content.
Example:
<details>
<summary>Click to learn more about HTML semantic elements</summary>
<p>Semantic HTML elements like <code><article></code>, <code><section></code>, <code><nav></code>, and <code><footer></code> help to provide meaning to web content, improving accessibility and SEO.</p>
<p>They are essential for building well-structured and understandable web pages.</p>
</details>
<details open>
<summary>Already open details</summary>
<p>This content is visible by default because the open attribute is present.</p>
</details>What is the difference between <div> and <span>?
Answer:
<div> is a block-level element used for grouping large content, while <span> is an inline element used for small portions of content.
Basic HTML Interview Questions
How would you implement a responsive navigation bar that transforms into a hamburger menu on mobile devices?
Answer:
Use a combination of media queries, flexbox, and JavaScript to toggle menu visibility. The hamburger icon should be properly labeled for accessibility.
Example:
<nav class="navbar">
<button class="hamburger" aria-expanded="false" aria-label="Menu">
<span></span>
<span></span>
<span></span>
</button>
<ul class="nav-links">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<style>
.navbar {
display: flex;
justify-content: space-between;
}
.hamburger {
display: none;
background: none;
border: none;
}
@media (max-width: 768px) {
.hamburger { display: block; }
.nav-links { display: none; }
.nav-links.active { display: block; }
}
</style>
<script>
document.querySelector('.hamburger').addEventListener('click', function() {
this.setAttribute('aria-expanded',
this.getAttribute('aria-expanded') === 'true' ? 'false' : 'true');
document.querySelector('.nav-links').classList.toggle('active');
});
</script>
Create an accessible modal dialog using the HTML5 <dialog> element.
Answer:
The <dialog> element provides built-in accessibility features when properly implemented with ARIA attributes and focus management.
Example:
<button id="openDialog">Open Modal</button>
<dialog id="myDialog" aria-labelledby="dialogTitle">
<h2 id="dialogTitle">Confirmation</h2>
<p>Are you sure you want to proceed?</p>
<button id="closeDialog">Close</button>
</dialog>
<script>
const dialog = document.getElementById('myDialog');
document.getElementById('openDialog').addEventListener('click', () => {
dialog.showModal();
document.getElementById('closeDialog').focus();
});
document.getElementById('closeDialog').addEventListener('click', () => {
dialog.close();
});
</script>
<style>
dialog::backdrop {
background: rgba(0,0,0,0.5);
}
dialog {
border: none;
box-shadow: 0 0 20px rgba(0,0,0,0.3);
}
</style>
Implement a dark/light theme switcher using CSS variables and localStorage.
Answer:
CSS variables allow dynamic theme changes, while localStorage maintains user preference across sessions.
Example:
<button id="themeToggle">Toggle Theme</button>
<script>
const toggle = document.getElementById('themeToggle');
if (localStorage.getItem('theme') === 'dark') {
document.documentElement.classList.add('dark');
}
toggle.addEventListener('click', () => {
document.documentElement.classList.toggle('dark');
localStorage.setItem('theme',
document.documentElement.classList.contains('dark') ? 'dark' : 'light'
);
});
</script>
<style>
:root {
--text: #333;
--bg: #fff;
}
.dark {
--text: #eee;
--bg: #222;
}
body {
color: var(--text);
background: var(--bg);
transition: all 0.3s ease;
}
</style>
How would you create a responsive image with multiple sources using the <picture> element?
Answer:
The <picture> element allows serving different image files based on device characteristics like screen size or pixel density.
Example:
<picture>
<source media="(min-width: 1200px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Description" loading="lazy">
</picture>
Create an accessible tab interface using ARIA attributes.
Answer:
ARIA roles and properties make tab interfaces understandable to screen readers and keyboard users.
Example:
<div role="tablist">
<button role="tab" aria-selected="true" aria-controls="panel1" id="tab1">Tab 1</button>
<button role="tab" aria-selected="false" aria-controls="panel2" id="tab2">Tab 2</button>
</div>
<div role="tabpanel" id="panel1" aria-labelledby="tab1">
<p>Content for Tab 1</p>
</div>
<div role="tabpanel" id="panel2" aria-labelledby="tab2" hidden>
<p>Content for Tab 2</p>
</div>
<script>
const tabs = document.querySelectorAll('[role="tab"]');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Tab switching logic here
});
});
</script>
Implement a responsive two-column layout that stacks on mobile using CSS Grid.
Answer:
CSS Grid provides a clean way to create responsive layouts without media query overload.
Example:
<div class="grid-container">
<aside>Sidebar</aside>
<main>Content</main>
</div>
<style>
.grid-container {
display: grid;
grid-template-columns: 250px 1fr;
gap: 20px;
}
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr;
}
}
</style>
How would you create a custom checkbox with pure CSS?
Answer:
Hide the native checkbox and style a pseudo-element or sibling element instead.
Example:
<label class="custom-checkbox">
<input type="checkbox">
<span class="checkmark"></span>
Option
</label>
<style>
.custom-checkbox input {
position: absolute;
opacity: 0;
}
.checkmark {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #333;
margin-right: 10px;
}
input:checked + .checkmark {
background-color: #2196F3;
}
</style>
Create a semantic HTML structure for a blog post with comments.
Answer:
Proper semantic markup improves SEO and accessibility while providing clear content structure.
Example:
<article>
<header>
<h1>Blog Post Title</h1>
<time datetime="2023-01-01">January 1, 2023</time>
</header>
<div class="post-content">
<p>Post content...</p>
</div>
<section class="comments">
<h2>Comments</h2>
<article class="comment">
<footer>
<span class="author">User</span>
<time datetime="2023-01-02">Jan 2</time>
</footer>
<p>Comment text...</p>
</article>
</section>
</article>
Implement a responsive table that scrolls horizontally on small screens.
Answer:
Contain the table in a scrollable div while keeping headers visible for better mobile UX.
Example:
<div class="table-container">
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>john@example.com</td>
<td>555-1234</td>
</tr>
</tbody>
</table>
</div>
<style>
.table-container {
overflow-x: auto;
max-width: 100%;
}
table {
width: 100%;
border-collapse: collapse;
}
@media (max-width: 768px) {
thead {
position: sticky;
left: 0;
background: white;
}
}
</style>
How would you implement a breadcrumb navigation using semantic HTML?
Answer:
Breadcrumbs should use ordered lists and proper ARIA labels for screen readers.
Example:
<nav aria-label="Breadcrumb">
<ol>
<li><a href="/">Home</a></li>
<li><a href="/products">Products</a></li>
<li aria-current="page">Current Page</li>
</ol>
</nav>
<style>
nav ol {
display: flex;
list-style: none;
padding: 0;
}
nav li:not(:last-child)::after {
content: "›";
margin: 0 10px;
}
[aria-current="page"] {
font-weight: bold;
}
</style>
Create a semantic product card with schema.org microdata.
Answer:
Schema.org markup helps search engines understand and display product information.
Example:
<article class="product-card" itemscope itemtype="https://schema.org/Product">
<img src="product.jpg" alt="Product Name" itemprop="image">
<h2 itemprop="name">Product Name</h2>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
<span itemprop="priceCurrency" content="USD">$</span>
<span itemprop="price" content="29.99">29.99</span>
</div>
<button>Add to Cart</button>
</article>
Advanced HTML Interview Questions
Explain the difference between the <script>, <script async>, and <script defer> attributes.
Answer:
<script> blocks HTML parsing until the script is fetched and executed. <script async> fetches the script asynchronously while HTML parsing continues, and executes it immediately once fetched. <script defer> also fetches asynchronously but waits to execute until HTML parsing is complete.
How would you implement a responsive image with different sources for different screen sizes?
Answer:
Using the <picture> element with <source> tags: <picture> <source media='(min-width: 1200px)' srcset='large.jpg'> <source media='(min-width: 768px)' srcset='medium.jpg'> <img src='small.jpg' alt='Responsive image'> </picture>
What is the purpose of the Shadow DOM? Provide a code example.
Answer:
Shadow DOM enables encapsulation for DOM and CSS. Example: const element = document.querySelector('#host'); const shadowRoot = element.attachShadow({mode: 'open'}); shadowRoot.innerHTML = `<style>p { color: red; }</style><p>Shadow DOM content</p>`;
Explain the difference between SVG and Canvas with appropriate use cases for each.
Answer:
SVG is vector-based and resolution-independent, best for logos/icons. Canvas is pixel-based, better for games/charts.
Example:
SVG:
<svg width='100' height='100'><circle cx='50' cy='50' r='40' fill='red'/></svg>
Canvas:
<canvas id='myCanvas' width='200' height='100'></canvas>How would you implement a custom data attribute and access it via JavaScript?
Answer:
HTML:
Example:
<div id='user' data-user-id='1234' data-role='admin'></div>
JavaScript:
const user = document.getElementById('user');
console.log(user.dataset.userId); // '1234'
console.log(user.dataset.role); // 'admin'What is the purpose of the <meta> tag with 'viewport' content? Write the proper tag.
Answer:
It controls layout on mobile browsers. Essential tag: <meta name='viewport' content='width=device-width, initial-scale=1.0'> This sets the viewport width to device width and initial zoom to 1.0.
Explain the difference between sessionStorage and localStorage with code examples.
Answer:
sessionStorage persists only for the session, localStorage persists until cleared. // Storing localStorage.setItem('key', 'value'); sessionStorage.setItem('sessionKey', 'sessionValue'); // Retrieving const value = localStorage.getItem('key'); const sessionValue = sessionStorage.getItem('sessionKey');
How would you implement a drag and drop interface using HTML5? Provide a complete example.
Answer:
HTML: <div id='drag' draggable='true'>Drag me</div> <div id='drop'>Drop here</div> JavaScript: drag.addEventListener('dragstart', (e) => e.dataTransfer.setData('text', e.target.id)); drop.addEventListener('dragover', (e) => e.preventDefault()); drop.addEventListener('drop', (e) => { e.preventDefault(); const id = e.dataTransfer.getData('text'); e.target.appendChild(document.getElementById(id)); });
What are Web Components and how would you create one?
Answer:
Web Components are custom, reusable HTML elements. Example: class MyComponent extends HTMLElement { constructor() { super(); this.attachShadow({mode: 'open'}); this.shadowRoot.innerHTML = `<p>Custom Element</p>`; } } customElements.define('my-component', MyComponent); Usage: <my-component></my-component>
How would you implement a video player with fallback content using HTML5?
Answer:
<video width='320' height='240' controls> <source src='movie.mp4' type='video/mp4'> <source src='movie.ogg' type='video/ogg'> Your browser does not support HTML5 video. </video>
Explain the difference between aria-label, aria-labelledby, and aria-describedby with examples.
Answer:
aria-label directly provides text: <button aria-label='Close'>X</button> aria-labelledby references another element: <div id='btnDesc'>Close</div><button aria-labelledby='btnDesc'>X</button> aria-describedby adds descriptive text: <input aria-describedby='dateFormat'><span id='dateFormat'>MM/DD/YYYY</span>
How would you implement a responsive table that scrolls horizontally on small screens?
Answer:
<div style='overflow-x:auto;'> <table> <!-- table content --> </table> </div> CSS alternative: @media screen and (max-width: 600px) { table { display: block; overflow-x: auto; } }
What is the purpose of the <template> tag? Provide a usage example.
Answer:
<template> stores HTML content not rendered immediately. Example: <template id='userTemplate'> <li class='user'> <span class='name'></span> </li> </template> JavaScript: const template = document.getElementById('userTemplate'); const clone = template.content.cloneNode(true); clone.querySelector('.name').textContent = 'John'; document.body.appendChild(clone);
How would you implement a geolocation feature in HTML5?
Answer:
JavaScript code: if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { console.log('Latitude:', position.coords.latitude); console.log('Longitude:', position.coords.longitude); }, (error) => console.error('Error:', error) ); } else { alert('Geolocation not supported'); }
Explain the difference between HTMLCollection and NodeList with code examples.
Answer:
HTMLCollection is live, NodeList is usually static. // HTMLCollection (live) const htmlCollection = document.getElementsByClassName('item'); // NodeList (static with querySelectorAll) const nodeList = document.querySelectorAll('.item'); // Convert NodeList to array const array = Array.from(nodeList);
How would you implement a web worker for background processing?
Answer:
Main script: const worker = new Worker('worker.js'); worker.postMessage('Start working'); worker.onmessage = (e) => console.log('Message from worker:', e.data); worker.js: onmessage = (e) => { console.log('Message from main:', e.data); // Heavy processing here postMessage('Work done'); };
What is the purpose of the <datalist> element? Provide an example.
Answer:
Provides autocomplete suggestions for input: <input list='browsers'> <datalist id='browsers'> <option value='Chrome'> <option value='Firefox'> <option value='Safari'> </datalist>
How would you implement a progress bar that updates in real-time?
Answer:
<progress id='progress' value='0' max='100'></progress> JavaScript: const progress = document.getElementById('progress'); let value = 0; const interval = setInterval(() => { value += 5; progress.value = value; if (value >= 100) clearInterval(interval); }, 500);
Explain the difference between display: none, visibility: hidden, and opacity: 0.
Answer:
display: none removes from layout. visibility: hidden hides but maintains space. opacity: 0 makes transparent but remains interactive. CSS: .hidden { display: none; } /* Gone */ .invisible { visibility: hidden; } /* Space kept */ .transparent { opacity: 0; } /* Still there */
How would you implement a modal dialog using only HTML (no JavaScript)?
Answer:
Using the <dialog> element: <dialog open> <p>This is a native HTML dialog!</p> <form method='dialog'> <button>Close</button> </form> </dialog> Note: For full functionality (open/close), JavaScript is typically needed.
What is the purpose of the <slot> element in Web Components? Provide an example.
Answer:
<slot> allows content projection in custom elements. Example: class MyComponent extends HTMLElement { constructor() { super(); this.attachShadow({mode: 'open'}); this.shadowRoot.innerHTML = ` <div> <slot name='header'>Default Header</slot> <slot>Default Content</slot> </div>`; } } Usage: <my-component> <h1 slot='header'>Custom Header</h1> <p>Custom Content</p> </my-component>
How would you implement a collapsible section without JavaScript?
Answer:
Using the <details> and <summary> elements: <details> <summary>Click to expand</summary> <p>Hidden content that appears when expanded</p> </details>
Explain the importance of the rel='noopener' attribute in anchor tags and when to use it.
Answer:
It prevents security vulnerabilities when opening links in new tabs: <a href='https://example.com' target='_blank' rel='noopener'>Safe Link</a> Without noopener, the new page can access the original page's window object via window.opener, which could be a security risk.
How would you implement a color picker using HTML5?
Answer:
Using the <input type='color'> element: <label for='colorpicker'>Choose a color:</label> <input type='color' id='colorpicker' name='colorpicker' value='#ff0000'> JavaScript to get value: document.getElementById('colorpicker').addEventListener('input', (e) => { console.log('Selected color:', e.target.value); });
What is the purpose of the <output> element? Provide an example.
Answer:
Represents the result of a calculation: <form oninput='result.value=parseInt(a.value)+parseInt(b.value)'> <input type='number' id='a' value='0'> + <input type='number' id='b' value='0'> = <output name='result' for='a b'>0</output> </form>
How would you implement a date picker with a minimum and maximum date?
Answer:
<input type='date' id='birthday' name='birthday' min='1900-01-01' max='2023-12-31'> JavaScript validation: const dateInput = document.getElementById('birthday'); dateInput.addEventListener('change', () => { const selected = new Date(dateInput.value); const min = new Date(dateInput.min); const max = new Date(dateInput.max); if (selected < min || selected > max) { alert('Date out of range'); dateInput.value = ''; } });
Explain the difference between the 'disabled' and 'readonly' attributes in form elements.
Answer:
disabled prevents interaction and excludes the field from form submission. readonly prevents editing but includes in submission. <input type='text' disabled value='Cannot change'> <input type='text' readonly value='Can copy but not edit'>
How would you implement a custom right-click (context) menu?
Answer:
HTML: <div id='contextArea'>Right-click here</div> <ul id='contextMenu' style='display:none;'> <li>Option 1</li> <li>Option 2</li> </ul> JavaScript: contextArea.addEventListener('contextmenu', (e) => { e.preventDefault(); contextMenu.style.display = 'block'; contextMenu.style.left = `${e.pageX}px`; contextMenu.style.top = `${e.pageY}px`; }); document.addEventListener('click', () => { contextMenu.style.display = 'none'; });
What is the purpose of the ping attribute in anchor tags?
Answer:
Sends a POST request to specified URLs when link is clicked: <a href='https://example.com' ping='https://analytics.com/track'>Link</a> When clicked, the browser will send a ping to the tracking URL in the background.
How would you implement a multi-file upload with previews before submission?
Answer:
HTML: <input type='file' id='upload' multiple> <div id='preview'></div> JavaScript: const upload = document.getElementById('upload'); const preview = document.getElementById('preview'); upload.addEventListener('change', () => { preview.innerHTML = ''; Array.from(upload.files).forEach(file => { const reader = new FileReader(); reader.onload = (e) => { const img = document.createElement('img'); img.src = e.target.result; img.width = 100; preview.appendChild(img); }; if (file.type.startsWith('image/')) { reader.readAsDataURL(file); } else { preview.innerHTML += `${file.name}<br>`; } }); });
Explain the purpose of the <meter> element and provide an example.
Answer:
Represents a scalar measurement within a known range: <label for='disk'>Disk usage:</label> <meter id='disk' value='65' min='0' max='100' low='30' high='80' optimum='60'> 65 out of 100 </meter> The browser will color the meter based on the value relative to the low/high thresholds.
How would you implement a real-time form validation using HTML5 attributes?
Answer:
Using built-in validation attributes: <form id='myForm'> <input type='text' required minlength='3' maxlength='20' pattern='[A-Za-z]+'> <input type='email' required> <input type='number' min='18' max='99'> <input type='submit'> </form> JavaScript for custom validation: myForm.addEventListener('submit', (e) => { if (!myForm.checkValidity()) { e.preventDefault(); alert('Please fill the form correctly'); } });
What is the purpose of the crossorigin attribute in script tags?
Answer:
It defines how the browser handles crossorigin requests: <script src='https://otherdomain.com/script.js' crossorigin='anonymous'></script> Possible values: - anonymous: No credentials sent - use-credentials: Send credentials Without it, error details for cross-origin scripts may be hidden.
How would you implement a notification system using the Notifications API?
Answer:
First request permission, then show notifications: // Request permission Notification.requestPermission().then(permission => { if (permission === 'granted') { new Notification('Title', { body: 'Notification content', icon: '/icon.png' }); } }); Note: This only works in secure contexts (HTTPS or localhost).
Explain the difference between the 'autocomplete' and 'autofill' features in forms.
Answer:
autocomplete is a HTML attribute that controls browser suggestions: <input type='text' name='username' autocomplete='username'> Autofill is a browser feature that fills forms based on saved data. autocomplete='off' can disable both, but modern browsers may ignore it for certain fields like passwords.
How would you implement a dark/light mode toggle that persists across page refreshes?
Answer:
HTML: <button id='themeToggle'>Toggle Theme</button> CSS: :root { --bg: white; --text: black; } .dark { --bg: black; --text: white; } body { background: var(--bg); color: var(--text); } JavaScript: const toggle = document.getElementById('themeToggle'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)'); // Check localStorage or prefered scheme if (localStorage.theme === 'dark' || (!localStorage.theme && prefersDark.matches)) { document.documentElement.classList.add('dark'); } toggle.addEventListener('click', () => { document.documentElement.classList.toggle('dark'); localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light'; });
What is the purpose of the <link rel='preload'> tag? Provide an example.
Answer:
Tells the browser to start loading critical resources early: <link rel='preload' href='font.woff2' as='font' type='font/woff2' crossorigin> <link rel='preload' href='critical.js' as='script'> <link rel='preload' href='hero-image.jpg' as='image'> This can significantly improve performance when used for above-the-fold resources.
How would you implement a virtual scrolling list for large datasets?
Answer:
Basic implementation: <div id='viewport' style='height: 500px; overflow-y: auto;'> <div id='content' style='height: 100000px;'> <!-- Visible items will be rendered here --> </div> </div> JavaScript: const viewport = document.getElementById('viewport'); const content = document.getElementById('content'); const itemHeight = 50; const totalItems = 1000; viewport.addEventListener('scroll', () => { const scrollTop = viewport.scrollTop; const startIdx = Math.floor(scrollTop / itemHeight); const endIdx = Math.min(startIdx + 10, totalItems); // Render only visible items content.innerHTML = ''; for (let i = startIdx; i < endIdx; i++) { const item = document.createElement('div'); item.style.height = `${itemHeight}px`; item.textContent = `Item ${i}`; content.appendChild(item); } });
Explain the purpose of the inert attribute and provide an example.
Answer:
The inert attribute makes an element and its children non-interactive: <div inert> <button>This button can't be clicked</button> <a href='#'>This link can't be focused</a> </div> It's useful for modals where you want to disable interaction with background content.
How would you implement a print-specific stylesheet?
Answer:
Using a media attribute: <link rel='stylesheet' media='print' href='print.css'> Or within a stylesheet: @media print { .no-print { display: none; } body { font-size: 12pt; } a::after { content: ' (' attr(href) ')'; } }
What is the purpose of the <base> tag and when would you use it?
Answer:
Specifies base URL for all relative URLs in the document: <head> <base href='https://example.com/path/'> </head> <body> <img src='images/photo.jpg'> <!-- Loads from https://example.com/path/images/photo.jpg --> </body> Use with caution as it affects all relative URLs. Useful for single-page applications or when serving pages from different directories.
How would you implement a contenteditable div with rich text formatting controls?
Answer:
HTML: <div id='editor' contenteditable></div> <button onclick='formatText("bold")'>Bold</button> <button onclick='formatText("italic")'>Italic</button> JavaScript: function formatText(cmd) { document.execCommand(cmd, false, null); } // For modern implementations, consider using the Clipboard API and Range/Selection APIs instead.
Explain the purpose of the manifest attribute in the <html> tag.
Answer:
Used for Progressive Web Apps (PWAs) to specify the app manifest: <html manifest='app.manifest'> Modern approach uses a link tag instead: <link rel='manifest' href='/manifest.webmanifest'> The manifest contains metadata like name, icons, start URL, display mode for installable web apps.
How would you implement a language selector that changes the page language without reloading?
Answer:
HTML: <select id='language'> <option value='en'>English</option> <option value='es'>Español</option> </select> JavaScript: language.addEventListener('change', () => { // Update content via JavaScript document.documentElement.lang = language.value; // Or fetch translations fetch(`/translations/${language.value}.json`) .then(res => res.json()) .then(translations => { document.querySelectorAll('[data-i18n]').forEach(el => { el.textContent = translations[el.dataset.i18n]; }); }); });
What is the purpose of the <optgroup> element in select dropdowns? Provide an example.
Answer:
Groups related options together: <select> <optgroup label='Fruits'> <option>Apple</option> <option>Banana</option> </optgroup> <optgroup label='Vegetables'> <option>Carrot</option> <option>Potato</option> </optgroup> </select>
How would you implement a countdown timer using the <time> element?
Answer:
HTML: <time id='countdown'>00:00:00</time> JavaScript: const end = new Date(); end.setHours(end.getHours() + 1); // 1 hour from now function updateTimer() { const now = new Date(); const diff = end - now; if (diff <= 0) { clearInterval(timer); countdown.textContent = 'Expired!'; return; } const hours = Math.floor(diff / (1000 * 60 * 60)); const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const secs = Math.floor((diff % (1000 * 60)) / 1000; countdown.textContent = `${hours}:${mins}:${secs}`; countdown.dateTime = end.toISOString(); } const timer = setInterval(updateTimer, 1000);
Explain the purpose of the integrity attribute in script/link tags.
Answer:
Enables Subresource Integrity (SRI) to verify resources haven't been tampered with: <script src='https://example.com/script.js' integrity='sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC' crossorigin='anonymous'></script> The browser compares the hash of the downloaded resource with the integrity value.
How would you implement a tabbed interface using ARIA attributes?
Answer:
HTML: <div role='tablist'> <button role='tab' aria-selected='true' aria-controls='panel1'>Tab 1</button> <button role='tab' aria-selected='false' aria-controls='panel2'>Tab 2</button> </div> <div role='tabpanel' id='panel1'>Content 1</div> <div role='tabpanel' id='panel2' hidden>Content 2</div> JavaScript: const tabs = document.querySelectorAll('[role="tab"]'); tabs.forEach(tab => { tab.addEventListener('click', () => { // Hide all panels document.querySelectorAll('[role="tabpanel"]').forEach(p => p.hidden = true); // Deselect all tabs tabs.forEach(t => t.setAttribute('aria-selected', 'false')); // Show selected panel const panel = document.getElementById(tab.getAttribute('aria-controls')); panel.hidden = false; // Select clicked tab tab.setAttribute('aria-selected', 'true'); }); });
What is the purpose of the <fieldset> and <legend> elements? Provide an example.
Answer:
Groups related form controls: <fieldset> <legend>Shipping Address</legend> <label>Street: <input type='text' name='street'></label> <label>City: <input type='text' name='city'></label> </fieldset> <fieldset> <legend>Billing Address</legend> <!-- billing fields --> </fieldset> Improves accessibility and visual grouping of related form elements.
How would you implement a service worker for offline functionality?
Answer:
Main script: if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(reg => console.log('SW registered')) .catch(err => console.log('SW registration failed:', err)); } sw.js: const CACHE_NAME = 'my-cache-v1'; const urlsToCache = ['/', '/styles.css', '/script.js']; self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => cache.addAll(urlsToCache)) ); }); self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => response || fetch(event.request)) ); });