HTML Basics to Advanced

  1. What is HTML?

  2. What are tags in HTML?

  3. Difference between HTML and HTML5 ?

  4. What is the purpose of the <!DOCTYPE html> declaration?

  5. What is the difference between <div> and <span> and ?

  6. What is the use of the <meta> tag?

  7. What is the difference between block-level and inline elements?

  8. What are different types of form elements in HTML?

  9. What’s the use of action, method, and enctype attributes in ?

  10. How do you create a dropdown list in HTML?

  11. What is the purpose of the fieldset and legend tags?

  12. How do you group form elements using the tag?

  13. What is the purpose of the alt attribute in images?

  14. What’s the difference between <a href=”#”> and <a href=”javascript:void(0)”>?

  15. What are global attributes in HTML? List a few.

  16. What is the use of the data-* attributes?

  17. Explain tabindex, accesskey, and contenteditable

  18. Whats the purpose of hidden attribute in HTML5?

  19. What is the difference between id and class attributes?

  20. What is the use of title attribute?

  21. What is the rel attribute in a or tag?

  22. How do you embed an image, video, or audio in HTML?

  23. What is the default character encoding in HTML5?

  24. Whats the difference between HTML, XML, and XHTML?

  25. What are conditional comments in HTML?

  26. How does the browser know which character set to use?

  27. How do browsers render HTML internally (DOM, Render Tree)?

  28. What is the difference between innerText, textContent, and innerHTML?

  29. What is progressive enhancement vs graceful degradation?

  30. Can two elements have the same id? Why or why not?

  31. What happens when you nest block elements inside inline elements?

  32. What is a favicon and how do you include it?

  33. What are meta tags important for performance or SEO?

  34. How do you handle HTML validation?

  35. What is Critical Rendering Path?

  36. How do you improve the loading speed of HTML pages?

  37. What is the difference between defer and async in script tag ?

  38. How do you ensure cross-browser compatibility in HTML?

  39. What are best practices for writing HTML?

  40. Difference between embed , object and iframe ?

  41. How do you create a responsive image?

  42. How does semantic HTML help with SEO?

  43. What are ARIA (Accessible Rich Internet Applications) attributes?

  44. How would you make a website accessible?

  45. Why is using headings (h1 to h6) properly important ?

  46. What is localStorage vs sessionStorage?

  47. What is the purpose of the <canvas> element?

  48. What is the <template> tag and when it is used ?

  49. How does HTML5 Geolocation API work?

What is HTML ?

Definition:
HTML stands for HyperText Markup Language. It is the standard markup language used to create the structure and content of web pages on the Internet.


💡 Breakdown of the Term:

  • HyperText: Refers to text with links (hyperlinks) that connect to other pages or resources. It allows users to navigate between documents or parts of the same document.

  • Markup Language: A way of annotating a document using tags to define the structure, meaning, and presentation of text and other content.


🏗️ Purpose of HTML:

  • To structure content on the web — for example:

    • Headings

    • Paragraphs

    • Images

    • Links

    • Lists

    • Tables

    • Forms

  • HTML provides the skeleton of a web page, which is then styled using CSS and made interactive using JavaScript.


🧩 Basic Structure of an HTML Document:

htmlCopyEdit<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
    <p>This is my first HTML page.</p>
  </body>
</html>

Explanation:

  • <!DOCTYPE html>: Declares the document as HTML5.

  • <html>: Root element of the HTML page.

  • <head>: Contains metadata, title, links to CSS or JS files.

  • <body>: Contains the visible content of the page.


📦 Key Features of HTML:

FeatureDescription
Platform IndependentWorks across all devices and browsers.
ExtensibleCan be used with CSS, JavaScript, frameworks like React, etc.
Semantic TagsHTML5 introduced tags like <article>, <section>, <nav> to provide better meaning.
Media SupportHTML supports audio, video, and images.
Form HandlingHTML forms are the foundation for collecting user input.

🧠 Interview Tip:

If asked, don't just say “HTML is a markup language” — talk about:

  • Its role in web development

  • How it works with CSS and JavaScript

  • Its structure (DOM tree)

  • Evolution (HTML4 vs HTML5)

What are tags in HTML?

🏷️ Definition:

Tags in HTML are the building blocks of an HTML document. They are keywords enclosed in angle brackets (< >) that define how web browsers should display and structure content on a webpage.


📌 Basic Syntax:

htmlCopyEdit<tagname>Content goes here</tagname>
  • The opening tag: <tagname>

  • The closing tag: </tagname>

  • The content lies between the two tags

Example:

htmlCopyEdit<p>This is a paragraph.</p>

🔁 Types of Tags:

TypeDescriptionExample
Paired TagsHave both opening and closing tags<h1>Title</h1>
Self-closing TagsDo not require a closing tag (mostly void elements)<br>, <img>, <hr>

🧩 Common HTML Tags and Their Use:

TagPurpose
<html>Root of the HTML document
<head>Metadata container
<title>Sets the page title
<body>Main content of the page
<h1><h6>Headings (largest to smallest)
<p>Paragraph
<a>Anchor (link) tag
<img>Embeds images
<ul> / <ol>Unordered / Ordered list
<li>List item
<div>Block-level container
<span>Inline container
<form>, <input>, <button>For user input

✨ HTML5 Semantic Tags:

These tags provide meaning to the structure and improve SEO and accessibility.

TagMeaning
<header>Page or section header
<footer>Page or section footer
<nav>Navigation links
<article>Independent content
<section>Group of related content
<aside>Sidebar or tangential info
<main>Main content of the document

🎯 Why Are Tags Important in HTML?

  • Define structure and hierarchy of content

  • Allow browsers to render content appropriately

  • Enable semantic meaning (helps with SEO and accessibility)

  • Serve as hooks for CSS and JavaScript


🧠 Interview Tip:

If you're asked “What are HTML tags?”, follow up with:

  • An explanation of paired vs self-closing

  • Some examples

  • Mention semantic tags if it's a modern HTML5 discussion

Difference between HTML and HTML5 ?

Difference Between HTML and HTML5

FeatureHTML (HTML 4.01 and below)HTML5 (Latest version)
DefinitionStandard markup language used to structure web pagesUpdated version with new features and capabilities
Doctype DeclarationLong and complexSimple and short
<!DOCTYPE HTML PUBLIC...><!DOCTYPE html>
Multimedia SupportNo native support – required third-party plugins like FlashBuilt-in support for audio and video using <audio> and <video> tags
New Semantic ElementsNot availableIntroduced: <header>, <footer>, <section>, <article>, etc.
Form ControlsBasic input types (text, password, etc.)New input types: email, date, range, search, etc.
APIs and FeaturesLacked built-in APIsIncludes Web Storage, Geolocation API, Canvas, WebSockets, etc.
Graphics and AnimationRequired external tools like Flash<canvas>, <svg> allow drawing and animations natively
Error HandlingLess consistent, browser-specificMore consistent error handling across modern browsers
Mobile and Responsive DesignNot supported inherentlyDesigned with mobile and responsive design in mind
Browser SupportOutdated – not fully compatible with modern browsersFully supported by all modern browsers

🧩 Examples:

📜 HTML Doctype in HTML vs HTML5

HTML 4.01 Doctype (long and hard to remember):

htmlCopyEdit<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

HTML5 Doctype (simple):

htmlCopyEdit<!DOCTYPE html>

✨ Semantic Tags in HTML5 (Not in HTML)

HTML:

htmlCopyEdit<div id="header">...</div>

HTML5:

htmlCopyEdit<header>...</header>

🧠 Interview Tip:

Emphasize that HTML5 is not a different language, but an evolution of HTML. It brings semantics, multimedia, mobile-friendliness, and API support, making web apps richer and more efficient without relying heavily on plugins.

What is the purpose of the declaration?

What is the purpose of the <!DOCTYPE html> declaration?


📌 Definition:

The <!DOCTYPE html> declaration is an instruction that tells the web browser which version of HTML the document is written in. It helps the browser render the page correctly and consistently.


💡 Purpose of <!DOCTYPE html>:

  1. Triggers Standards Mode

    • Ensures that the browser renders the HTML document using the standard rendering rules, not older or quirky legacy behaviors.

    • Without it, browsers may switch to "quirks mode", where outdated rendering models are used to support older sites.

  2. Defines HTML Version

    • In HTML5, the doctype is simplified to:

        <!DOCTYPE html>
      
    • This tells the browser: “Use HTML5 rules to interpret this page.”

  3. Ensures Cross-Browser Consistency

    • Helps maintain uniform behavior across different web browsers like Chrome, Firefox, Safari, and Edge.

    • Prevents bugs and layout issues caused by different rendering modes.


📜 HTML Doctype Evolution:

VersionDoctype Declaration
HTML 4.01<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"...>
XHTML 1.0<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"...>
HTML5<!DOCTYPE html> ✅ (much simpler)

🔍 What Happens Without It?

If you omit <!DOCTYPE html>, the browser may:

  • Enter quirks mode

  • Ignore some CSS styles

  • Misrender box models, fonts, layouts, etc.

  • Cause inconsistent behavior across browsers


🧠 Interview Tip:

When asked this in an interview, you should cover:

  • Its role in telling the browser the HTML version

  • The difference between standards mode vs quirks mode

  • The simplicity of HTML5 doctype and how it improves compatibility

What is the difference between and ?

Difference Between <div> and <span> in HTML


🔍 Quick Answer:

Feature<div><span>
TypeBlock-level elementInline element
Default BehaviorStarts on a new line, takes full widthDoes not start on a new line, takes only as much width as needed
Use CaseFor grouping larger sections or block elementsFor styling or manipulating inline text or parts of elements
StylingOften used with CSS for layoutOften used with CSS for inline styling
Semantic MeaningNo semantic meaningNo semantic meaning

🧱 1. <div> (Block-Level Element)

  • Used to group larger content blocks (paragraphs, images, sections).

  • Often used for layout and page structure.

  • Default behavior: breaks to a new line.

<div>
  <h2>Profile</h2>
  <p>This is a user profile section.</p>
</div>

🔹 This will render:

  • The <h2> and <p> start on new lines.

  • The <div> acts as a container for them.


✏️ 2. <span> (Inline Element)

  • Used to group small chunks of text or inline elements.

  • Commonly used to apply styles or scripts to parts of a sentence.

  • Default behavior: does not break to a new line.

<p>Hello, <span style="color: blue;">Siddhanth</span>!</p>

🔹 This will render:

  • “Hello,” and “Siddhanth!” appear on the same line

  • Only "Siddhanth" is styled blue


📌 Real-Life Analogy:

  • <div> is like a box or container that holds big blocks (e.g., sections of a website).

  • <span> is like a highlighter pen you use to style a few words in a sentence.


🎯 When to Use:

  • Use <div> for layout and structure

  • Use <span> for inline styling or logic


🧠 Interview Tip:

Always mention:

  • Block vs inline behavior

  • Layout vs text-level usage

  • Common use cases with CSS and JavaScript

What is the use of the <meta> tag?

What is the use of the <meta> tag in HTML?


📌 Definition:

The <meta> tag is used in the <head> section of an HTML document to provide metadata—i.e., data about the page—to the browser and search engines.

It does not display any content on the web page but plays a crucial role in SEO, character encoding, responsiveness, and browser behavior.


🧠 Key Uses of <meta> Tag:

Use CaseWhat It Does
Character EncodingSpecifies the character set (e.g., UTF-8) to properly display text
Viewport SettingsMakes the layout responsive on mobile devices
SEO and KeywordsHelps search engines understand page content via keywords and description
Page DescriptionSets the description that appears in search engine results
Author InformationDefines the page's author
Auto-Refresh/RedirectAllows automatic refresh or redirect after a time delay
Control CachingTells the browser how to handle page caching

📜 Examples of Common <meta> Tags:

1. Character Encoding (very important!)

<meta charset="UTF-8">
  • Ensures the text displays correctly (e.g., special characters like é, €, ✓)

2. Responsive Design (Viewport Settings)

<meta name="viewport" content="width=device-width, initial-scale=1.0">
  • Makes the website mobile-friendly by controlling layout scaling on small screens.

3. SEO: Page Description

<meta name="description" content="A beginner-friendly HTML tutorial website."
  • This may appear as the snippet in Google search results.

4. SEO: Keywords (less used nowadays)

<meta name="keywords" content="HTML, CSS, web development, tutorial">
  • Provides search engines with topic keywords (used less now due to abuse).

5. Author Information

<meta name="author" content="Siddhanth Chauhan">
  • Specifies the page creator.

6. Auto Refresh or Redirect

<meta http-equiv="refresh" content="5; url=https://example.com">
  • Redirects to another URL after 5 seconds.

7. Control Caching

<meta http-equiv="Cache-Control" content="no-cache">
  • Prevents the browser from caching the page.

📍 Where Is It Used?

  • Placed inside the <head> tag:
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="An HTML tutorial for beginners.">
</head>

🧠 Interview Tip:

When asked this, don’t just say "for metadata". Talk about:

  • Character encoding

  • SEO relevance

  • Mobile responsiveness

  • Use in browser behavior (refresh/redirect, cache control)

What is the difference between block-level and inline elements?

Difference Between Block-Level and Inline Elements in HTML


🔍 Overview:

In HTML, every element has a default display behavior—either:

  • Block-level (takes up the full width)

  • Inline (takes up only as much width as needed)

Understanding this distinction is crucial for layout, styling, and page structure.


📌 Comparison Table:

FeatureBlock-Level ElementsInline Elements
Display BehaviorStarts on a new lineStays on the same line with other elements
WidthTakes full width by defaultTakes only as much width as needed
HeightCan be set (height, padding, margin apply fully)Height usually depends on content
Use CaseLayout structure, large containersText formatting, styling small parts of content
Can containBlock-level & inline elementsOnly text or inline elements
Customizable with CSSYesYes, but more limited than block elements

🧱 Block-Level Elements:

  • Create a new block of content.

  • Often used for structural layout.

📜 Examples:

<div>Section</div>
<p>Paragraph</p>
<h1>Heading</h1>
<ul>
  <li>List Item</li>
</ul>
<section>Content block</section>

✅ These will each appear on separate lines in the browser.


✏️ Inline Elements:

  • Do not start on a new line.

  • Used to style or manipulate small portions of text within a block.

📜 Examples:

<span>Highlighted text</span>
<a href="#">Link</a>
<strong>Bold</strong>
<em>Italic</em>
<img src="..." alt="Image">

✅ These will appear inline with surrounding text.


📊 Visual Example:

<p>This is a <span style="color: red;">red word</span> inside a paragraph.</p>
  • The paragraph (<p>) is block-level

  • The <span> is inline, just coloring one word


🧠 Interview Tip:

When asked about block vs inline:

  • Always mention line behavior, width handling, and typical use cases

  • Consider giving real HTML examples

  • If time allows, mention that CSS display: block or display: inline can override the default behavior

What are different types of form elements in HTML?

Different Types of Form Elements in HTML


HTML forms allow users to input data, which can then be sent to a server for processing. Forms consist of various form elements, each serving a specific purpose.


🧾 Commonly Used Form Elements:

ElementDescription
<input>Generic form element used for many input types (text, email, number, etc.)
<textarea>Multi-line text input
<select>Drop-down list
<option>Defines options within a <select>
<button>Clickable button
<label>Provides a caption for form controls
<fieldset>Groups related elements in a form
<legend>Title for a <fieldset> group
<form>Wraps all form elements; used to submit user data
<datalist>Defines a list of pre-defined options for <input>
<output>Displays result of a calculation
<input type="hidden">Stores hidden data, not visible to users

🖊️ Detailed Breakdown of <input> Types:

The <input> tag is extremely versatile. Here are the major types:

Input TypePurpose
type="text"Single-line text input
type="password"Hides characters for passwords
type="email"Validates email format
type="number"Accepts only numeric input
type="radio"Select one option from a group
type="checkbox"Select multiple options
type="submit"Submits the form
type="reset"Resets all fields to their default values
type="file"Allows file upload
type="date"Date picker
type="range"Slider input
type="color"Color picker
type="tel"Phone number input
type="url"URL input with basic validation
type="search"Search field (browser-specific styling)
type="hidden"Stores background data, not visible to user
type="button"Regular button (custom functionality via JS)

📜 Example Form:

<form action="/submit" method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="username" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email">

  <label for="message">Message:</label>
  <textarea id="message" name="message"></textarea>

  <label for="gender">Gender:</label>
  <select id="gender" name="gender">
    <option value="male">Male</option>
    <option value="female">Female</option>
  </select>

  <input type="submit" value="Submit">
</form>

🧠 Interview Tip:

Mention:

  • How <input> is flexible due to type attribute

  • When to use <textarea>, <select>, and <datalist>

  • Importance of <label> for accessibility

  • Grouping with <fieldset> and <legend>

Whats the use of action, method, and enctype attributes in ?

Great question! These three attributes—action, method, and enctype—are critical for how HTML forms send data to a server.


Use of action, method, and enctype in <form>


🔹 1. action attribute

📌 What it does:
Specifies the URL where the form data will be sent when submitted.

<form action="/submit-form">
  • If action is omitted, the form submits to the current page URL.

  • This URL can be:

🧠 Interview Insight: Think of action as the “destination” for your data.


🔹 2. method attribute

📌 What it does:
Specifies the HTTP method to use when submitting the form.

<form method="GET"> or <form method="POST">

🔸 GET method:

  • Appends data to the URL as query parameters (e.g., ?name=John)

  • Visible in the URL

  • Less secure, suitable for non-sensitive data (like search queries)

  • Has length limitations (~2000 characters)

🔸 POST method:

  • Sends data in the request body

  • Not visible in the URL

  • More secure, ideal for login forms, file uploads, etc.

  • No size limit (depends on server)

🧠 Interview Insight:
Use GET for retrieving data, POST for sending or updating data.


🔹 3. enctype attribute

📌 What it does:
Defines how the form data should be encoded before sending to the server.

Used only with method="POST".

<form enctype="multipart/form-data">

Common Values:

ValueWhen to Use
application/x-www-form-urlencodedDefault for most forms, encodes data as key-value pairs
multipart/form-dataFor file uploads, required with <input type="file">
text/plainRarely used, sends data without encoding

Example with File Upload:

<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="resume">
  <input type="submit" value="Upload">
</form>

🧠 Summary Table:

AttributePurposeCommon Values
actionDestination URL for form submission/submit, https://example.com/api/send
methodHTTP method used to send dataGET, POST
enctypeEncoding type for submitted data (POST only)application/x-www-form-urlencoded, multipart/form-data

🧠 Interview Tip:

If asked:

  • Explain when to use each method

  • Mention how enctype is required for file uploads

  • Bonus: talk about security implications of GET vs POST

How do you create a dropdown list in HTML?

How to Create a Dropdown List in HTML

A dropdown list in HTML is created using the <select> element, along with nested <option> elements that define the selectable items.


🧾 Basic Syntax:

<label for="fruits">Choose a fruit:</label>
<select id="fruits" name="fruit">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="mango">Mango</option>
</select>

🧠 Explanation:

  • <select>: Defines the dropdown list.

    • id: Used to link with a <label> for accessibility.

    • name: The key used when the form is submitted.

  • <option>: Each selectable item inside the dropdown.

    • value: The actual data sent to the server when that option is selected.

    • The text between the <option> tags is what the user sees.


Attributes You Can Use:

selected

Specifies a default selected option.

<option value="mango" selected>Mango</option>

disabled

Disables an option or even the entire dropdown.

<option value="none" disabled>--Select Fruit--</option>

multiple

Allows the user to select multiple options (shows a list box instead of a single dropdown).

<select name="fruits" multiple>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="mango">Mango</option>
</select>

size

Specifies the number of options visible at once (for listbox-style dropdowns).

<select name="fruits" size="3">

🧠 Interview Tip:

If asked how to create a dropdown:

  • Start with a basic <select> and <option> example.

  • Mention name, value, and selected.

  • Bonus: Mention multiple, disabled, and accessibility with <label>.


🧪 Example with All Features:

<form>
  <label for="cars">Choose a car:</label>
  <select id="cars" name="car" required>
    <option value="" disabled selected>Select your car</option>
    <option value="tesla">Tesla</option>
    <option value="bmw">BMW</option>
    <option value="audi">Audi</option>
  </select>
  <button type="submit">Submit</button>
</form>

What is the purpose of the fieldset and legend tags?

Purpose of <fieldset> and <legend> Tags in HTML


📌 Purpose:
The <fieldset> tag is used to group related elements in a form to create a logical section. This is especially useful for long forms with multiple categories like personal info, billing info, etc.

🎯 Benefits:

  • Enhances accessibility

  • Improves readability and structure

  • Can be styled to visually separate sections (browsers often add a box border by default)


🔹 2. <legend>Label the Group

📌 Purpose:
The <legend> tag provides a caption or title for the <fieldset>, describing the content of that group.

  • It must be the first element inside <fieldset>

  • Screen readers use it to announce section context, improving accessibility


📜 Example:

<form>
  <fieldset>
    <legend>Personal Information</legend>

    <label for="name">Name:</label>
    <input type="text" id="name" name="name">

    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
  </fieldset>

  <fieldset>
    <legend>Preferences</legend>

    <label><input type="checkbox" name="newsletter"> Subscribe to newsletter</label>
    <label><input type="checkbox" name="updates"> Receive product updates</label>
  </fieldset>

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

🧠 Visual Effect:

  • <fieldset> adds a box around the grouped inputs.

  • <legend> appears as a title within that box.


🧠 Interview Tip:

If asked:

  • Explain that <fieldset> is for grouping related form fields

  • Mention that <legend> provides a caption for that group

  • Highlight accessibility and usability benefits

How do you group form elements using the tag?

How to Group Form Elements Using the <optgroup> Tag


The <optgroup> tag in HTML is used within a <select> dropdown to group related <option> elements under a common label. It improves the organization and readability of long dropdown lists, especially when options fall under different categories.


🧾 Basic Syntax:

<select name="cars">
  <optgroup label="Electric">
    <option value="tesla">Tesla</option>
    <option value="nissan">Nissan Leaf</option>
  </optgroup>
  <optgroup label="Gasoline">
    <option value="ford">Ford Mustang</option>
    <option value="chevy">Chevrolet Camaro</option>
  </optgroup>
</select>

🧠 Explanation:

  • <optgroup>: Creates a labeled group of related <option> elements.

    • label: The heading shown in the dropdown for that group.
  • <option>: Individual items the user can select.

  • <optgroup> must go inside <select> and can contain only <option> tags (not other <optgroup> tags).


Visual Representation:

When the user clicks the dropdown, it will look something like:

Electric
  - Tesla
  - Nissan Leaf
Gasoline
  - Ford Mustang
  - Chevrolet Camaro

(Visually grouped, though the appearance depends on the browser.)


❌ Invalid Nesting Example (Not Allowed):

<optgroup label="Group 1">
  <optgroup label="Subgroup"> <!-- ❌ Nested optgroup is invalid -->
    <option>Option</option>
  </optgroup>
</optgroup>

Additional Notes:

  • You can disable an entire group:
<optgroup label="Unavailable Cars" disabled>
  <option>Tata Nano</option>
</optgroup>

🧠 Interview Tip:

If asked:

  • Explain that <optgroup> is used for categorizing dropdown options

  • Mention the label attribute and disabling feature

  • Emphasize its use for better UX and accessibility in large forms

What is the purpose of the alt attribute in images?

Purpose of the alt Attribute in <img> Tags

The alt (alternative text) attribute in HTML is used within an <img> tag to provide descriptive text about the image.


🔍 Syntax:

<img src="logo.png" alt="Company Logo">

🎯 Main Purposes of alt Attribute:


1. Accessibility

  • Screen readers use the alt text to describe the image to visually impaired users.

  • Makes your website more inclusive and ADA-compliant.

🧠 Example:
A blind user using a screen reader will hear:

“Company Logo” instead of just silence or "image".


2. Fallback Text 🧱

  • If the image fails to load (broken link, slow connection, etc.), the alt text is displayed in place of the image.

🧠 Example:

<img src="wrong-path.jpg" alt="Beautiful sunset over the mountains">

If the image doesn't load, the browser will show:
“Beautiful sunset over the mountains”


3. SEO Benefits 📈

  • Search engines can't see images, but they can read alt text.

  • Helps improve image search rankings and overall SEO.


What NOT to Do:

  • Don't stuff it with keywords just for SEO.

  • Don't leave it blank unless the image is purely decorative.

Example for decorative image:

<img src="border.png" alt="">

🧠 Interview Tip:

If asked:

  • Emphasize accessibility, fallback behavior, and SEO

  • Provide an example of proper alt usage

  • Mention it's required for valid HTML and good practice

What’s the difference between <a href=”#”> and <a href=”javascript:void(0)”>?

🔍 Difference Between <a href="#"> and <a href="javascript:void(0)">

Both of these anchor tags are often used in situations where you don’t want the link to navigate anywhere or reload the page, but they behave differently and are used in different contexts.


<a href="#">Click me</a>

🔸 What it does:

  • Navigates to the top of the page (jumps to id="top" or the default page top).

  • Used as a placeholder link during development.

🔸 Problems:

  • Causes the page to scroll to top.

  • May alter browser history or cause unintended navigation.

  • Less ideal in SPA (Single Page App) or JS-heavy environments.


✅ 2. <a href="javascript:void(0)"> — Executes JS Without Reload

<a href="javascript:void(0)">Click me</a>

🔸 What it does:

  • Calls JavaScript and does nothing (void(0) returns undefined).

  • Prevents page reload and scrolling.

  • Commonly used when a link is purely for triggering JavaScript actions (e.g. toggling modals or triggering events).


🧠 Example Use Cases:

Use Case<a href="#"><a href="javascript:void(0)">
Placeholder during design/dev
Trigger JavaScript without navigation
Avoid scroll to top
SEO-friendly and semantic✅ (with proper href)

✅ Best Practice (Modern Approach)

In most modern development, especially with React/Next.js or SPAs:

🔸 Prefer using a button or onClick handler if the element doesn't navigate:

<button onclick="toggleModal()">Open Modal</button>

Or with semantic HTML:

<a href="#" onclick="toggleModal(); return false;">Open Modal</a>

🧠 Interview Tip:

If asked:

  • Explain that <a href="#"> scrolls to top, while <a href="javascript:void(0)"> does nothing.

  • Highlight their typical use cases.

  • Bonus: Recommend using button for actions instead of misusing <a>.

What are global attributes in HTML? List a few.

🌐 What Are Global Attributes in HTML?

Global attributes are HTML attributes that can be applied to any HTML element, regardless of its type.

They are called “global” because they are universally supported across all HTML elements and provide extra functionality, such as styling, accessibility, or interactivity.


✅ Why Are They Important?

  • Add common behavior (like id, class, style) to any tag

  • Improve accessibility, JavaScript interactions, and CSS targeting

  • Help in internationalization, custom data handling, etc.


🧾 Common Global Attributes

AttributePurpose
idUniquely identifies an element
classAssigns one or more CSS classes
styleAdds inline CSS styles
titleAdds a tooltip that appears on hover
hiddenHides the element from the page
tabindexControls keyboard navigation order
accesskeyDefines a keyboard shortcut for the element
contenteditableMakes an element editable by the user
draggableSpecifies whether the element can be dragged
langDeclares the language of the element's content
dirSets text direction (ltr, rtl, auto)
data-*Used to store custom data for JavaScript use

🔍 Example:

<div id="info" class="box" style="color: blue;" title="Hover text" data-user-id="123">
  Hello World!
</div>

In the above example:

  • id, class, and style apply styles and CSS targeting

  • title shows a tooltip

  • data-user-id can be accessed using JavaScript like:

      document.getElementById('info').dataset.userId; // "123"
    

🧠 Interview Tip:

If asked:

  • Explain that global attributes can be added to any HTML tag

  • Mention a few commonly used ones: id, class, style, title, data-*

  • Bonus: Mention accessibility-related attributes like lang, dir, or tabindex

What is the use of the data-* attributes?

🔍 What Is the Use of the data-* Attributes in HTML?

The data-* attributes in HTML allow you to store custom data on any HTML element. These are known as custom data attributes, and they are incredibly useful for adding extra, non-visible information that can be easily accessed using JavaScript.


✅ Syntax:

<div data-user-id="12345" data-role="admin">John Doe</div>

🎯 Why Use data-* Attributes?

  • Store custom information without affecting HTML semantics.

  • Avoid using non-standard attributes (which are invalid).

  • Keep your HTML clean and decoupled from logic.

  • Easily accessible via JavaScript using .dataset.


📦 Example Use Case:

HTML:

<button data-product-id="789" data-price="499">Buy Now</button>

JavaScript:

const btn = document.querySelector("button");

const productId = btn.dataset.productId; // "789"
const price = btn.dataset.price;         // "499"

✅ Key Points:

FeatureDescription
PrefixAlways starts with data- followed by a custom name
Valid HTMLComplies with HTML5 specs
Accessible in JSThrough element.dataset (camelCase format)
ScopedBelongs only to the element where it's defined

🧠 Use Cases:

  • Storing user IDs, roles, or statuses

  • Managing filtering/sorting values

  • Passing data for modals, tooltips, tabs

  • Configuring animation or UI behavior without bloating JS logic


⚠️ Caution:

  • Don’t use data-* to store sensitive information (not secure).

  • Don't overuse it when the data is already available in your JavaScript.


🧠 Interview Tip:

If asked:

  • Explain it's used to store custom data in HTML.

  • Mention it's valid, semantic, and JavaScript-friendly.

  • Show an example of accessing data-* with .dataset.

Explain tabindex, accesskey, and contenteditable

Great! Here's a detailed breakdown of tabindex, accesskey, and contenteditable — three HTML global attributes that enhance accessibility and interactivity.


✅ 1. tabindex — Controls Keyboard Focus Order

🔸 What it does:

tabindex defines the order in which elements receive focus when the user presses the Tab key.

🔹 Values:

ValueMeaning
0Includes the element in the tab order (after default focusable elements).
>0Sets a custom order (lower values are focused first).
-1Makes the element focusable via JavaScript, but not with Tab key.

🧾 Example:

<input type="text" tabindex="2">
<input type="text" tabindex="1">
<button tabindex="3">Click</button>

Focus order will be: 2nd input ➝ 1st input ➝ button


✅ 2. accesskey — Assigns a Keyboard Shortcut

🔸 What it does:

Gives the user a way to activate/focus an element using a keyboard shortcut, enhancing accessibility and speed.

🔹 Usage:

  • The specific key combo depends on the browser and OS:

    • Windows: Alt + accesskey

    • macOS: Ctrl + Alt + accesskey (or Control + Option in Safari)

🧾 Example:

<button accesskey="s">Save</button>

On Windows, pressing Alt + S will activate the "Save" button.


✅ 3. contenteditable — Makes Elements Editable

🔸 What it does:

Turns any HTML element into an editable text field — like a mini text editor.

🔹 Values:

  • "true" — Editable

  • "false" — Not editable

  • (If the attribute is present without a value, it's treated as "true")

🧾 Example:

<div contenteditable="true">Edit this text</div>

You can now type directly inside this <div> in the browser.


📋 Summary Table:

AttributePurposeTypical Use
tabindexDefines tab focus orderAccessibility / Custom focus management
accesskeyAssigns a keyboard shortcutSpeed & accessibility improvements
contenteditableMakes content user-editableIn-browser editing, CMS, WYSIWYG editors

🧠 Interview Tip:

If asked:

  • Explain their purpose with examples

  • Emphasize keyboard accessibility and user interaction

  • Bonus: Mention contenteditable is useful for creating custom editors or notes apps

Whats the purpose of hidden attribute in HTML5?

🔍 What Is the Purpose of the hidden Attribute in HTML5?

The hidden attribute is a boolean global attribute introduced in HTML5. It is used to hide an element from the user interface — i.e., it won’t be displayed on the page.


✅ Syntax:

<p hidden>This paragraph is hidden.</p>

You can also use it like:

<p hidden="hidden">Hidden again</p>

But simply using hidden is sufficient, since it's a boolean attribute.


🎯 Purpose & Behavior:

FeatureDescription
VisibilityHides the element from the page — behaves like display: none; in CSS
LayoutThe element is not rendered, so it doesn't occupy space in layout
AccessibilityScreen readers usually do not read hidden elements (but this may vary)
Script UseUseful for show/hide elements dynamically with JavaScript

🧾 JavaScript Example:

You can toggle the visibility using JavaScript:

<p id="secret" hidden>This is a hidden message.</p>
<button onclick="document.getElementById('secret').hidden = false">Reveal</button>

This makes the hidden paragraph visible when the button is clicked.


✅ Comparison with style="display: none;":

Featurehidden Attributestyle="display: none"
SemanticYes (HTML5-native way)No (pure CSS)
CSS OverridableNo (requires JS or attribute removal)Yes (can be overridden with CSS)
Recommended UseHTML-level controlCSS-level styling control

⚠️ Notes:

  • Don’t confuse hidden with visibility: hidden (which hides the element but keeps its space).

  • Removing the hidden attribute will show the element:

      element.removeAttribute("hidden");
    

🧠 Interview Tip:

If asked:

  • Say it’s a global HTML5 attribute that hides elements from rendering.

  • Compare it briefly to display: none and mention that it’s not accessible by default.

  • Show a use case where it's toggled using JavaScript.

What is the difference between id and class attributes?

🔍 Difference Between id and class Attributes in HTML

Both id and class are global attributes used to identify and style HTML elements, but they serve different purposes and have different rules.


🔹 id Attribute

✅ Purpose:

Used to uniquely identify a single element on the page.

✅ Characteristics:

  • Must be unique within the entire HTML document.

  • Often used for:

    • JavaScript DOM manipulation

    • Linking with anchor tags (#id)

    • Targeting specific elements via CSS

🧾 Example:

<div id="header">Site Header</div>

🔧 CSS:

#header {
  background-color: blue;
}

🔸 class Attribute

✅ Purpose:

Used to group multiple elements under the same name for styling or scripting.

✅ Characteristics:

  • Can be reused on multiple elements.

  • Elements can have multiple classes (space-separated).

  • Preferred for general styling.

🧾 Example:

<div class="card">Card 1</div>
<div class="card">Card 2</div>

🔧 CSS:

.card {
  border: 1px solid gray;
  padding: 10px;
}

🔄 Comparison Table

Featureidclass
UniquenessMust be unique per pageCan be used on many elements
Reusability❌ Not reusable✅ Reusable
Syntax in CSS#id.class
Best Use CaseJS targeting, anchor linkingStyling, grouped behavior
Multiple Values❌ Only one id per element✅ Multiple classes allowed

⚠️ Best Practices

  • Use id for:

    • Unique elements like #nav, #footer, #main-content

    • JavaScript selectors when you want to target a specific element

  • Use class for:

    • Styling reusable components

    • Grouping elements with similar behavior


🧠 Interview Tip:

If asked:

  • Say "id is for uniquely identifying one element; class is for grouping multiple elements."

  • Mention that id uses # in CSS, class uses ..

  • Add that only one id is allowed per element, but multiple classes can be used.

What is the use of title attribute?

🔍 What Is the Use of the title Attribute in HTML?

The title attribute provides additional information about an HTML element. When the user hovers over the element, most browsers display the title value as a tooltip.


✅ Purpose of title:

  • Shows supplementary info to the user.

  • Helps with usability and accessibility.

  • Can enhance user experience by explaining unclear elements, icons, or abbreviations.


🧾 Example:

<button title="Click to submit your form">Submit</button>

🔁 When you hover over the button, a small tooltip will appear:
"Click to submit your form"


🔸 Where It Can Be Used:

The title attribute is a global attribute, so it can be used on any HTML element, including:

  • <a>, <img>, <abbr>, <button>, <input>, <div>, etc.

📌 Example with <abbr> (abbreviation):

<abbr title="HyperText Markup Language">HTML</abbr>

💡 When hovered, users see the full form: "HyperText Markup Language"


⚠️ Notes & Accessibility:

  • Screen readers may or may not read the title attribute, depending on the assistive technology.

  • Don't rely solely on title for conveying critical information — use visible text or ARIA attributes where necessary.

  • It's not a replacement for proper labeling in forms or buttons.


🚫 Common Misuses:

  • Using long paragraphs in the title — tooltips are meant for brief info.

  • Repeating visible text in the title (offers no extra value).

  • Relying on title for mobile devices — many touch interfaces don’t show tooltips.


🧠 Interview Tip:

If asked:

  • Say it's used to display tooltip text on hover.

  • Mention it's a global attribute that works on any element.

  • Highlight it's helpful but not a reliable method for accessibility alone.

What is the rel attribute in a or tag?

🔍 What Is the rel Attribute in <link> and <a> Tags?

The rel (short for “relationship”) attribute defines the relationship between the current document and the linked resource. It's commonly used in <link> and <a> tags to give semantic meaning to the link.


✅ 1. In <link> Tags (External Resources)

📌 Purpose:

Used in the <head> section to link external resources like stylesheets, icons, or prefetch data.

🧾 Common Usage:

<link rel="stylesheet" href="styles.css">

🔁 This tells the browser: "The linked file is a CSS stylesheet."

🔸 Other Examples:

rel ValueDescription
stylesheetLinks a CSS file
iconLinks a favicon
manifestLinks a web app manifest file
preloadPreloads a resource for performance
canonicalSpecifies the preferred URL for SEO
alternateLinks an alternate version of the page (like a translated page or RSS feed)

📌 Purpose:

Defines the relationship between the current document and the linked document.

🧾 Example:

<a href="https://example.com" rel="noopener noreferrer" target="_blank">Visit Site</a>

🔁 This improves security and performance when opening a link in a new tab.

🔸 Common rel Values for <a>:

rel ValueMeaning
noopenerPrevents the new page from accessing window.opener (security)
noreferrerPrevents sending referrer info to the target site
nofollowTells search engines not to follow the link (SEO)
externalDenotes an external link
licenseRefers to the license for the document
ugcMarks the link as User Generated Content (comments, forums)

🧠 Why rel="noopener noreferrer" Matters:

When using target="_blank", not adding rel="noopener" can lead to security risks like:

  • The new page accessing your page using window.opener

  • Potential phishing or redirect attacks

Adding noopener ensures better security and performance.


📋 Summary Table

TagPurpose of relExample
<link>Describes the relationship to external resourcesrel="stylesheet"
<a>Describes the relationship between the pagesrel="noopener noreferrer"

🧠 Interview Tip:

If asked:

  • Say rel defines the relationship between the current document and the linked resource.

  • In <link>, it helps browsers understand the purpose of external files (e.g., stylesheets).

  • In <a>, it enhances SEO, security, and semantics.

  • Mention noopener noreferrer for secure external links.

How do you embed an image, video, or audio in HTML?

🔍 How Do You Embed an Image, Video, or Audio in HTML?

In HTML, you can embed multimedia content like images, videos, and audio using specific tags:

  • <img> for images

  • <video> for video files

  • <audio> for audio files

These tags allow browsers to load and render rich content directly in web pages.


🖼️ 1. Embedding an Image with <img>

✅ Syntax:

<img src="path/to/image.jpg" alt="Description of image" width="300" height="200">

🔸 Attributes:

AttributePurpose
srcSource URL of the image
altAlternate text (important for accessibility & SEO)
width / heightControls image size
titleTooltip text on hover (optional)

🎥 2. Embedding a Video with <video>

✅ Syntax:

<video width="600" controls>
  <source src="video.mp4" type="video/mp4">
  <source src="video.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

🔸 Attributes:

AttributePurpose
controlsDisplays play/pause buttons, volume, etc.
autoplayStarts playing automatically
loopLoops the video
mutedStarts video muted
posterShows an image before the video plays

🧠 You should always include multiple <source> formats for broader browser support.


🔊 3. Embedding Audio with <audio>

✅ Syntax:

<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>

🔸 Attributes:

AttributePurpose
controlsShows play/pause, volume controls
autoplayPlays audio on page load
loopRepeats audio
mutedStarts muted

📌 Summary Table

ElementTagCommon AttributesPurpose
Image<img>src, alt, width, heightEmbed images
Video<video>controls, autoplay, loop, posterEmbed and control video playback
Audio<audio>controls, autoplay, loopEmbed and control audio

🧠 Interview Tip:

If asked:

  • Say <img>, <video>, and <audio> are the primary HTML tags for embedding multimedia.

  • Mention important attributes like src, controls, and alt.

  • Emphasize fallback content (like text inside <video> or <audio>) for unsupported browsers.

  • Mention best practices like including multiple <source> elements and using the alt attribute for accessibility.

What is the default character encoding in HTML5?

🔍 What Is the Default Character Encoding in HTML5?

The default character encoding in HTML5 is UTF-8.


✅ What Is UTF-8?

UTF-8 (Unicode Transformation Format - 8 bit) is a universal character encoding capable of representing every character in the Unicode standard. It's the most widely used and recommended encoding for web content.

  • Supports virtually all languages and symbols.

  • Backward compatible with ASCII.

  • Efficient in terms of file size for English and similar languages.


🔧 How to Declare UTF-8 in HTML5?

In HTML5, you declare the character encoding in the <head> section using the <meta> tag:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My HTML Page</title>
</head>
<body>
  ...
</body>
</html>

✅ This is the recommended minimal and valid way to declare UTF-8 in HTML5.


🧠 Why It's Important

  • Ensures correct rendering of text, especially non-English characters (like emojis 😊, accented letters, or Asian scripts).

  • Prevents encoding-related bugs (like question marks or garbled characters).

  • Essential for internationalization (i18n) and multi-language support.


❗ Without Declaring UTF-8

If you don’t declare the charset, the browser may try to guess the encoding, which can:

  • Cause inconsistent rendering across browsers/devices.

  • Break forms, scripts, and text content.

  • Affect SEO and accessibility.


🧠 Interview Tip:

If asked:

  • Say HTML5 uses UTF-8 as the default character encoding.

  • Mention it ensures correct rendering of a wide range of characters.

  • Highlight the importance of this line: <meta charset="UTF-8">

Whats the difference between HTML, XML, and XHTML?

🔍 Difference Between HTML, XML, and XHTML

HTML, XML, and XHTML are all markup languages, but they serve different purposes and follow different rules. Let’s break them down clearly:


🧾 1. HTML (HyperText Markup Language)

✅ Purpose:

Used to create web pages and display content in web browsers.

🔹 Characteristics:

  • Designed for structure and presentation.

  • Not strict — browsers are forgiving of errors.

  • Doesn’t require closing all tags.

  • Case-insensitive: <DIV> and <div> are the same.

🧪 Example:

<p>This is HTML.</p>

🧾 2. XML (eXtensible Markup Language)

✅ Purpose:

Used to store and transport data. It’s not for displaying data like HTML.

🔹 Characteristics:

  • Focused on data structure, not appearance.

  • Very strict syntax.

  • You define your own tags.

  • Tags must be closed and properly nested.

  • Case-sensitive.

🧪 Example:

<book>
  <title>Learning XML</title>
  <author>John Smith</author>
</book>

🧾 3. XHTML (eXtensible HyperText Markup Language)

✅ Purpose:

A stricter version of HTML that follows XML rules.

🔹 Characteristics:

  • Combines the structure of HTML with XML syntax rules.

  • All tags must be closed, properly nested.

  • All tag names must be lowercase.

  • Attributes must be quoted.

🧪 Example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head><title>XHTML Example</title></head>
  <body>
    <img src="image.jpg" alt="Image" />
  </body>
</html>

📊 Comparison Table

FeatureHTMLXMLXHTML
PurposeDisplay content in browsersStore and transport dataDisplay with XML strictness
Tag definitionPredefined tagsUser-defined tagsHTML tags + XML rules
Tag caseCase-insensitiveCase-sensitiveCase-sensitive (lowercase)
Closing tagsOptional in many casesMandatoryMandatory
Error handlingForgivingStrictStrict
Supported in browserYesNo (needs processing)Yes (but less common today)

🧠 Interview Tip:

If asked:

  • HTML is for structure and presentation of web pages.

  • XML is for data storage and transfer.

  • XHTML is HTML + XML, stricter and more consistent.

👉 Modern development uses HTML5 over XHTML due to its simplicity and flexibility.

What are conditional comments in HTML?

🔍 What Are Conditional Comments in HTML?

Conditional comments are a feature in HTML that was used to target specific versions of Internet Explorer (IE) with custom HTML or CSS.

They allowed developers to write IE-only code to fix layout bugs or apply different styles—without affecting other browsers.

⚠️ Note: Conditional comments only work in Internet Explorer (IE 5–9). They are ignored by all modern browsers, including IE 10+ and Edge.


✅ Syntax and Examples

📘 1. Basic Syntax:

<!--[if IE]>
  <p>This is shown only in Internet Explorer.</p>
<![endif]-->

📘 2. Targeting Specific Versions:

▶ Target Only IE 6:

<!--[if IE 6]>
  <link rel="stylesheet" href="ie6-styles.css">
<![endif]-->

▶ Target IE 9 and below:

<!--[if lte IE 9]>
  <script src="legacy-support.js"></script>
<![endif]-->

▶ Target IE Greater Than 7:

<!--[if gt IE 7]>
  <p>This is IE 8 and above.</p>
<![endif]-->

💡 Operators You Can Use

OperatorMeaning
IEAny version of Internet Explorer
lt IE 9Less than IE 9
lte IE 8Less than or equal to IE 8
gt IE 6Greater than IE 6
gte IE 7Greater than or equal to IE 7

📦 Use Case Example:

<!--[if lte IE 8]>
  <link rel="stylesheet" href="ie8-and-below.css">
<![endif]-->

✅ This loads a fallback CSS file only for IE8 and below, which lacked support for many modern CSS features.


❌ Deprecated in Modern Web Development

  • Microsoft dropped support for conditional comments in IE 10 and newer.

  • Today, feature detection using JavaScript (like Modernizr) or CSS feature queries is the recommended approach.


🧠 Interview Tip:

If asked:

  • Conditional comments were used to target specific IE versions.

  • Only supported in IE 5–9.

  • Useful for fixing browser-specific bugs.

  • Deprecated now in favor of progressive enhancement, feature detection, and graceful degradation.

How does the browser know which character set to use?

🌐 How Does the Browser Know Which Character Set to Use?

The browser knows which character set (encoding) to use based on:


✅ 1. <meta charset="..."> Tag in the HTML

The most common and reliable way to specify the character set is by using this tag in the <head>:

<meta charset="UTF-8">

This tells the browser:

“Use UTF-8 encoding to interpret the characters on this page.”

📝 UTF-8 is the default and recommended encoding in HTML5.


✅ 2. HTTP Headers from the Server

The server can also specify the charset via the Content-Type header:

Content-Type: text/html; charset=UTF-8

If the server sends this, the browser usually prioritizes it over the <meta> tag — but only if it comes early enough in the HTTP response.


✅ 3. Byte Order Mark (BOM)

In some files (especially UTF-16 or UTF-32), a BOM at the beginning of the file helps the browser detect the encoding automatically.

However, UTF-8 BOM is optional and often discouraged in web pages because it can cause subtle issues.


❗ What Happens Without a Charset?

If no charset is declared:

  • The browser may guess the encoding based on content — which can be unreliable.

  • It could fall back to older encodings like ISO-8859-1 or use system defaults.

  • This can result in mojibake (garbled or unreadable characters), especially for non-English content.


  • Supports all Unicode characters (languages, emojis, symbols).

  • Widely supported by browsers and tools.

  • Helps avoid character corruption issues.


🧠 Interview Tip:

If asked:

  • Browsers detect encoding using <meta charset>, HTTP headers, or BOM.

  • UTF-8 is the standard and best practice.

  • Always declare the charset early in the HTML <head> to ensure consistent rendering.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Character Encoding Example</title>
</head>
<body>
  ...
</body>
</html>

How do browsers render HTML internally (DOM, Render Tree)?

Great question! Understanding how browsers render HTML internally is crucial for writing efficient, performance-optimized web applications.


🧠 How Do Browsers Render HTML Internally?

The browser goes through several steps from receiving raw HTML to displaying pixels on the screen.

Here’s a simplified breakdown of the Browser Rendering Pipeline:


🔁 1. HTML Parsing → DOM Tree

The browser reads the HTML file from top to bottom and creates a tree-like structure called the DOM (Document Object Model).

Example:

<html>
  <body>
    <h1>Hello</h1>
    <p>World</p>
  </body>
</html>

Creates:

Document
 └── html
      └── body
           ├── h1
           └── p

✅ DOM = HTML structure in memory


🎨 2. CSS Parsing → CSSOM Tree

The browser also parses all the CSS (inline, internal, or external) and creates a CSSOM (CSS Object Model).

Example:

h1 {
  color: red;
}

Becomes:

CSSStyleSheet
 └── Rule: h1 { color: red }

✅ CSSOM = Styles in memory


🌲 3. DOM + CSSOM → Render Tree

The browser combines the DOM and CSSOM to create a Render Tree, which only includes visible elements (e.g., excludes <head>, scripts, or elements with display: none).

Render Tree:

RenderObject (html)
 └── RenderObject (body)
       ├── RenderObject (h1)
       └── RenderObject (p)

Each node includes visual properties like color, size, font, etc.


📐 4. Layout Phase (Reflow)

The browser calculates the position and size of each element based on the render tree.

This step answers:

“Where does each element go on the screen?”


🖌️ 5. Painting

Now the browser converts the render tree into actual pixels — it draws borders, text, colors, shadows, etc., onto the screen.


🎞️ 6. Compositing

If parts of the page are rendered on different layers (e.g., due to position, transform, z-index), the browser composites them together in the correct order and sends them to the GPU for final rendering.


🧠 Summary Diagram:

HTML + CSS
   ↓
Parse HTML → DOM
Parse CSS  → CSSOM
   ↓
Combine → Render Tree
   ↓
Layout (Reflow)
   ↓
Paint
   ↓
Composite → Screen

🧰 Developer Tools Insight

You can see this process in Chrome DevTools:

  • Elements tab → Shows the DOM

  • Styles tab → CSSOM rules

  • Performance tab → Shows timeline of layout, paint, and compositing events


🧠 Interview Tip:

If asked how browsers render HTML:

  • They parse HTML and CSS into DOM and CSSOM

  • Combine them into the Render Tree

  • Perform layout, painting, and compositing

  • Finally, pixels are drawn to the screen

What is the difference between innerText, textContent, and innerHTML?

This is a frequently asked and important JavaScript + HTML interview question. Here's a clear and in-depth comparison of innerText, textContent, and innerHTML:


🔍 Quick Summary

PropertyReturns/ModifiesIncludes Hidden Text?Parses HTML?Faster?
innerTextVisible text only, styled by CSS❌ No❌ No❌ Slow
textContentAll text content, visible or not✅ Yes❌ No✅ Fast
innerHTMLHTML + text inside an element✅ Yes✅ Yes❌ Medium

🧪 Let's Explore with an Example:

<div id="sample">
  Hello <span style="display: none;">Hidden</span> <b>World</b>
</div>

JavaScript:

let el = document.getElementById("sample");

console.log(el.innerText);     // "Hello World"
console.log(el.textContent);   // "Hello Hidden World"
console.log(el.innerHTML);     // "Hello <span style="display: none;">Hidden</span> <b>World</b>"

📌 Detailed Explanation:

innerText

  • Returns only visible text, based on current CSS.

  • Triggers a layout reflow (slower performance).

  • Ignores content with display: none or visibility: hidden.

📌 Example:

el.innerText = "New Text";  // Replaces all visible text inside

textContent

  • Returns all text, regardless of CSS visibility.

  • Faster because it doesn't reflow or parse styles.

  • Best for quickly reading/modifying raw textual content.

📌 Example:

el.textContent = "Quick update";  // Updates all text inside

innerHTML

  • Returns the entire HTML content (tags + text).

  • Allows you to inject or replace HTML structure.

  • Can be risky (XSS) if you’re inserting untrusted user input.

📌 Example:

el.innerHTML = "<span style='color:red'>Updated</span>";

🧠 When to Use What?

Use CaseRecommended Property
Just get/set visible textinnerText
Need all textual content (fast)textContent
Get/set HTML structure or tagsinnerHTML

🧠 Interview Tip:

Q: What's the difference between innerText, textContent, and innerHTML?

A:

  • innerText: Only visible text, affected by CSS. Triggers reflow.

  • textContent: All text, fast, ignores styling.

  • innerHTML: Full HTML content, including tags. Allows HTML manipulation.

What is progressive enhancement vs graceful degradation?

Excellent question! Both progressive enhancement and graceful degradation are web development strategies used to ensure your website works across a wide range of devices, browsers, and user capabilities — but they take opposite approaches.


🧠 Key Difference Summary

StrategyStarts WithFocuses OnExample Use Case
Progressive EnhancementBasic functionalityAdding features for modern browsersBuild mobile-friendly, then enhance for desktop
Graceful DegradationFull functionalityEnsuring core content works on older browsersDesktop site that still works on older phones

🔷 1. Progressive Enhancement (PE)

📌 Concept:

Start with a basic, functional version of the site (HTML), and enhance it step-by-step using CSS, JavaScript, or other modern features — if the browser supports them.

✅ Benefits:

  • Works for all users, even with slow connections or old browsers

  • Mobile-first and accessible

  • Encourages semantic HTML and performance

🧱 Layered Approach:

  1. Basic content and functionality with HTML

  2. Style with CSS (if supported)

  3. Enhance interactivity with JavaScript (if available)

🚀 Example:

<!-- Basic HTML form that works everywhere -->
<form action="/submit" method="POST">
  <input name="email" required>
  <button type="submit">Subscribe</button>
</form>

<!-- JavaScript added only if supported -->
<script>
  if ('fetch' in window) {
    // Add Ajax functionality
  }
</script>

🔶 2. Graceful Degradation (GD)

📌 Concept:

Start by building the full experience using modern technologies, and then ensure it still works acceptably if some features fail or are unsupported.

✅ Benefits:

  • Focuses on delivering rich experience to most users

  • Backward compatibility is considered after the main build

🔁 Example:

Build an interactive chart with WebGL or SVG, but provide a fallback image for older browsers:

<div id="chart"></div>
<noscript>
  <img src="fallback-chart.png" alt="Static Chart Image">
</noscript>

🧠 Analogy

Imagine making a cupcake:

  • Progressive Enhancement: Start with a plain cupcake (HTML), then add frosting (CSS), and then sprinkles (JS) if ingredients are available.

  • Graceful Degradation: Start with a fully decorated cupcake, but if some toppings fall off in delivery, at least the cake is still edible.


💬 Interview Tip:

Q: What's the difference between progressive enhancement and graceful degradation?

A:

  • Progressive Enhancement builds the site from a basic core, enhancing it step-by-step for modern browsers.

  • Graceful Degradation starts with a fully-featured site and ensures it still works acceptably in older or limited environments.

Can two elements have the same id? Why or why not?

Great question — one that’s frequently asked in interviews to test your understanding of DOM structure and HTML best practices.


❓ Can Two Elements Have the Same id?

Technically:
👉 Yes, two elements can have the same id, but...

Practically and semantically:
They should not.


📜 What the HTML Specification Says

The id attribute must be unique within a document.

So, while the browser won’t crash if you duplicate an id, you’re breaking the rules of proper HTML — which can cause bugs, unexpected behavior, and accessibility issues.


🔍 Why Should IDs Be Unique?

1. Document.querySelector / getElementById

These methods return the first matching element, so if there are duplicates, you'll only get the first one — leading to bugs.

<div id="user">Alice</div>
<div id="user">Bob</div>
document.getElementById("user").textContent  // Will return "Alice"

You can't easily access "Bob" — it breaks predictable scripting.


2. CSS Targeting

Using duplicated IDs in CSS can cause unpredictable styling:

#user {
  color: red;
}

Only one element may appear styled correctly depending on the rendering order.


When linking to an element via #id, only the first occurrence is recognized.

<a href="#section1">Jump to Section</a>

If there are multiple id="section1", the browser doesn’t know which one to scroll to.


4. Accessibility Concerns

Assistive technologies rely on unique ids to map labels, forms, and controls properly. Duplicates may confuse screen readers or break form accessibility.


✅ Correct Usage

Use class if you need to style or select multiple elements:

<div class="user">Alice</div>
<div class="user">Bob</div>
document.querySelectorAll(".user")  // NodeList of all users

Use id only when you need a single, uniquely identifiable element.


💬 Interview Tip:

Q: Can two elements have the same id?

A:
Technically yes, but it's against the HTML spec. id must be unique within a document. Duplicating IDs can cause unexpected behavior in DOM selection, CSS styling, anchor navigation, and accessibility — so you should never reuse IDs.

What happens when you nest block elements inside inline elements?

This is an excellent and subtle HTML interview question — it tests your knowledge of HTML semantics and browser rendering rules.


🧠 Short Answer:

Nesting block-level elements inside inline elements is invalid in HTML.

⚠️ It breaks HTML semantics, and while browsers may still render it, behavior is unpredictable and inconsistent.


🧱 HTML Display Types Recap:

  • Inline elements (like <span>, <a>, <strong>):

    • Do not start on a new line

    • Cannot contain block-level elements

    • Only hold text or other inline elements

  • Block-level elements (like <div>, <p>, <section>):

    • Start on a new line

    • Can contain inline or block elements


❌ Invalid Nesting Example:

<span>
  <div>This is invalid HTML</div>
</span>

🔎 What Happens?

  • This violates HTML5 content model rules.

  • Browsers like Chrome will autocorrect by:

    • Closing the <span> early, then placing the <div> outside.

    • The actual rendered DOM might look like:

        <span></span>
        <div>This is invalid HTML</div>
      

So even though the code looks like nesting, the browser fixes it behind the scenes.


✅ Valid Structure Example:

You should do it the other way around — nest inline inside block:

<div>
  <span>This is fine</span>
</div>

This is valid and standard HTML.


🚨 Why This Matters:

  1. Invalid HTML = unpredictable behavior

  2. CSS might not work correctly

  3. Accessibility tools (screen readers) may misinterpret

  4. DOM scripting can break due to unexpected element locations


✅ How to Fix It?

If you need to wrap a block-level element with styling or scripting, use a block-level wrapper like <div>, or change your inline element to a block-level tag (like <span><div> or <p>).


💬 Interview Tip:

Q: What happens when you nest a block element inside an inline element?

A: It’s invalid HTML. Inline elements should only contain inline or text nodes. Browsers may fix the structure automatically, often moving the block-level element outside of the inline tag, leading to unexpected rendering and bugs. You should always follow the HTML content model rules.

What is a favicon and how do you include it?

A great and often-overlooked interview question! Let’s dive into what a favicon is and how to use it correctly.


🧠 What is a Favicon?

A favicon (short for "favorite icon") is the small icon displayed in the browser tab, bookmark list, and history entries next to the webpage title.

📌 Commonly seen as:

  • The logo of a website in the browser tab

  • An icon in your bookmarks

  • An app icon when saved to a home screen on mobile


🛠️ How to Include a Favicon in HTML

✅ Basic Method (HTML5 Standard):

Place this inside the <head> tag:

<link rel="icon" href="/favicon.ico" type="image/x-icon">

✅ Modern Method (supports more formats and sizes):

<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="icon" href="/favicon.png" sizes="32x32" type="image/png">

You can even add multiple sizes and types for better cross-device support:

<!-- PNG favicon for browsers -->
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">

<!-- Apple Touch Icon (for iOS) -->
<link rel="apple-touch-icon" href="/apple-touch-icon.png">

📂 Where to Put the Favicon File?

  • Place favicon.ico (or .png, .svg) in the root directory (/) of your website.

  • This makes it accessible at https://yourdomain.com/favicon.ico (browsers often request this path by default).


🎨 File Format Tips

  • .ico: Best supported across all browsers

  • .png: High quality, modern, no animation

  • .svg: Scalable, lightweight, but not supported by all older browsers

  • Recommended size: 16x16, 32x32, or even 180x180 (for retina displays)


🔍 Browser Behavior

  • Some browsers auto-fetch /favicon.ico even if not linked explicitly

  • But for full control and reliability, always use the <link rel="icon"> tag


💬 Interview Tip

Q: What is a favicon and how do you include it in a web page?

A:
A favicon is a small icon shown in the browser tab and bookmarks. It helps users visually identify the site.
You include it using the <link rel="icon" href="path/to/icon.png"> tag inside the <head> section.
Favicons can be .ico, .png, or .svg files, and should ideally be placed in the root directory of the website.

What are meta tags important for performance or SEO?

Excellent question! Meta tags are essential in HTML for providing metadata (information about the webpage), and some of them play a critical role in SEO (Search Engine Optimization) and performance. Let's explore both aspects in depth:


✅ What Are Meta Tags?

Meta tags are placed inside the <head> section of an HTML document. They are not displayed on the page but are used by browsers, search engines, and social media platforms to understand the content and behavior of the page.


🔍 Important Meta Tags for SEO

  1. <meta name="description" content="...">

    • Purpose: Summarizes the page content.

    • SEO Impact: Used by search engines as the snippet in search results.

    • ✅ Keep it under 160 characters, concise, and keyword-rich.

    <meta name="description" content="Learn HTML meta tags for SEO and performance.">
  1. <meta name="robots" content="index, follow">

    • Purpose: Controls how search engine bots index your page.

    • Values:

      • index / noindex: Whether to include in search.

      • follow / nofollow: Whether to follow links.

    • Example:

        <meta name="robots" content="index, follow">
      
  1. <meta property="og:*"> (Open Graph tags)

    • Purpose: Improve social media sharing.

    • Not direct SEO, but enhances click-through rate via better preview cards.

    • Example:

        <meta property="og:title" content="Meta Tags Explained">
        <meta property="og:description" content="Learn important meta tags for SEO and performance.">
        <meta property="og:image" content="/preview.jpg">
      
  1. <meta name="viewport"> (Also affects SEO)

    • Purpose: Makes site mobile-responsive, which affects rankings on mobile.

    • Required for mobile-first indexing.

    • Example:

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      

🚀 Meta Tags That Impact Performance

  1. <meta http-equiv="Content-Type"> (Rare now)

    • Used in older HTML versions; in HTML5, use <meta charset="UTF-8"> instead.
  1. <meta charset="UTF-8">

    • Purpose: Defines character encoding.

    • Should be placed at the very top of <head> to prevent page re-rendering.

    <meta charset="UTF-8">
  1. <meta http-equiv="X-UA-Compatible" content="IE=edge">

    • Purpose: Ensures latest rendering engine in Internet Explorer.

    • Important for legacy support.

  1. <meta http-equiv="refresh" content="X; url=...">

    • Purpose: Redirects the page after X seconds.

    • ⚠️ Avoid for SEO — use server-side redirects instead.


⚠️ Common Pitfalls

  • Missing description: Can hurt click-through rates.

  • Keyword stuffing in meta tags: No longer effective — may hurt ranking.

  • No viewport tag: Site won’t be mobile-friendly, affecting mobile SEO.


💬 Interview Tip

Q: What meta tags are important for SEO and performance?

A:
For SEO, key meta tags include description, robots, and viewport — they help search engines understand your page, control indexing, and improve mobile compatibility.
For performance, charset helps ensure proper text rendering, and viewport ensures responsive design. Using Open Graph tags also boosts social sharing, improving visibility.

How do you handle HTML validation?

Great question! HTML validation ensures that your HTML follows proper syntax and standards. It helps catch errors, typos, and accessibility issues, making your site more robust, SEO-friendly, and cross-browser compatible — which is critical from an interview and real-world development perspective.


✅ What Is HTML Validation?

HTML validation is the process of checking HTML code against the standards defined by the W3C (World Wide Web Consortium) to ensure that it is well-formed and semantically correct.


📌 Why Is Validation Important?

  • 🧹 Finds mistakes like unclosed tags, misplaced attributes, and incorrect nesting.

  • 🌍 Improves browser compatibility (especially on older/less forgiving browsers).

  • 📈 Boosts SEO – search engines prefer valid, semantic markup.

  • Improves accessibility for screen readers and assistive tech.

  • 🧩 Helps debugging – clean code is easier to maintain and extend.


🛠️ How Do You Handle HTML Validation?

1. 🔍 Use the W3C Validator (Online Tool)

The official way:

👉 Visit: https://validator.w3.org/

You can validate by:

  • Pasting code

  • Entering a URL

  • Uploading an HTML file

It will show:

  • ✅ Pass/fail status

  • 🛑 Errors and ⚠️ warnings with line numbers and suggestions


2. 🧩 Use IDE/Editor Validation (Live Feedback)

Modern editors have built-in or plugin-based validators:

  • VS Code Extensions:

    • HTMLHint

    • W3C Web Validator

  • WebStorm, Sublime, Atom also have linters/validators.

  • Shows inline errors as you code (real-time).


3. 🚦 HTML Validators in CI/CD Pipeline

In larger projects:

  • Add HTML validation as part of automated tests or GitHub Actions.

  • Tools like:

    • html-validate

    • htmlhint

    • npm html-validator

npx html-validator --file=index.html --verbose

This ensures every commit or pull request passes HTML checks.


4. ✅ Use Browser DevTools

  • Open DevTools → Console → Look for HTML warnings/errors.

  • Tools like Lighthouse (in Chrome) also check semantic and accessibility violations.


🔄 Common Issues Validators Catch

❌ Issue✅ Fix
Unclosed tags<div> with no closing </div>
Nested block inside inline<span><div></div></span> → invalid
Deprecated tags (<font>, etc.)Use CSS instead
Missing alt on imagesAdd alt="description"
Missing DOCTYPE or charsetAdd <!DOCTYPE html> and <meta charset>

💬 Interview Answer Example:

Q: How do you handle HTML validation?

A:
I validate HTML by using the W3C Validator to check for structural and semantic issues. I also use editor plugins like HTMLHint for real-time linting and include validation in CI pipelines for automated checks. This helps catch issues early, improves browser compatibility, and ensures better accessibility and SEO.

What is Critical Rendering Path?

The Critical Rendering Path (CRP) is a core concept in web performance optimization and is commonly asked in frontend interviews. It refers to the sequence of steps the browser takes to convert HTML, CSS, and JavaScript into pixels on the screen — in other words, how your code becomes a visual web page.


🚀 Why Is CRP Important?

  • It directly impacts how fast a page loads and displays.

  • Understanding it helps you optimize for First Contentful Paint (FCP) and Largest Contentful Paint (LCP) — important metrics for user experience and Core Web Vitals (used by Google for SEO rankings).


🔧 Steps in the Critical Rendering Path

Here’s a breakdown of the steps the browser follows:

  1. HTML Parsing → DOM Construction

    • The browser parses HTML and builds the DOM (Document Object Model).

    • HTML is parsed top to bottom, and it may block rendering if external resources (like CSS or JS) are encountered.

  1. CSS Parsing → CSSOM Construction

    • CSS files are downloaded and parsed to build the CSSOM (CSS Object Model).

    • This step is render-blocking — the page cannot be painted without styles.

  1. JavaScript Execution (Optional)

    • If a <script> tag is encountered:

      • Parsing pauses.

      • Script is downloaded and executed.

      • It might modify the DOM or CSSOM.

  1. Render Tree Construction

    • Combines the DOM and CSSOM into a Render Tree.

    • Only visible elements are included — hidden ones (e.g., display: none) are excluded.

  1. Layout (Reflow)

    • Calculates the position and size of elements (box model).

    • Produces the geometry for rendering.

  1. Painting

    • Each node in the render tree is painted on the screen pixel by pixel.

    • Can be costly, especially with large or complex UI.


🧠 CRP Visualization

HTML    → DOM
CSS     → CSSOM
         ↓
   DOM + CSSOM → Render Tree → Layout → Paint → Composite

📉 What Can Slow Down the CRP?

  • Large CSS files (especially unused CSS)

  • Synchronous JavaScript (blocking the DOM/CSSOM build)

  • Too many fonts or large images

  • Render-blocking resources in the <head>


⚙️ CRP Optimization Techniques

  1. Minimize critical resources
    → Remove unused CSS/JS, compress files

  2. Defer non-critical JS
    → Use defer or async attributes:

     <script src="app.js" defer></script>
    
  3. Inline critical CSS
    → Include only above-the-fold CSS in <head>, load the rest asynchronously

  4. Lazy load images and fonts
    → Use loading="lazy" for images

  5. Use modern formats
    → Use WebP for images, preload key fonts and assets

  6. Reduce DOM size and complexity


💬 Interview Answer Template

Q: What is the Critical Rendering Path?

A:
The Critical Rendering Path is the sequence of steps the browser takes to convert HTML, CSS, and JavaScript into pixels on the screen. It involves building the DOM and CSSOM, combining them into a render tree, performing layout (reflow), and finally painting the content.
Optimizing the CRP is essential for improving page load speed and user experience. Techniques include deferring non-critical scripts, inlining critical CSS, lazy-loading assets, and minimizing render-blocking resources.

How do you improve the loading speed of HTML pages?

Improving the loading speed of HTML pages is crucial for providing a great user experience, boosting SEO rankings, and reducing bounce rates. In interviews, this question evaluates your understanding of web performance optimization, including Critical Rendering Path, resource management, and best practices.


🔧 Practical Ways to Improve Loading Speed

1. Minimize HTTP Requests

  • Fewer requests mean faster load times.

  • How:

    • Combine CSS/JS files where possible.

    • Use CSS sprites for icons.

    • Eliminate unnecessary third-party scripts.


2. Use async and defer for Scripts

  • Scripts block HTML parsing unless controlled.
<script src="script.js" async></script> <!-- Loads & executes independently -->
<script src="script.js" defer></script> <!-- Loads in parallel, runs after DOM -->

3. Minify HTML, CSS, and JavaScript

  • Removes whitespace, comments, and unnecessary characters.

  • Tools: html-minifier, cssnano, uglify-js

npx html-minifier input.html -o output.html

4. Compress with Gzip or Brotli

  • Reduces file size before transmission.

  • Usually enabled via server configuration (.htaccess, NGINX, etc.).


5. Use a Content Delivery Network (CDN)

  • Delivers assets from geo-distributed servers, reducing latency.

  • Best for static resources: images, CSS, JS.


6. Lazy Load Images and Videos

  • Load them only when they're about to enter the viewport.
<img src="image.jpg" loading="lazy" alt="...">

7. Optimize Images

  • Resize and compress images before use.

  • Prefer modern formats like WebP, AVIF.

# Use tools like:
imagemin, Squoosh, TinyPNG

8. Preload Critical Resources

  • Tell the browser to prioritize key assets early.
<link rel="preload" href="style.css" as="style">

9. Use Inline Critical CSS

  • Inline only the CSS needed for above-the-fold content.

  • Load the rest asynchronously.


10. Reduce DOM Size and Depth

  • A large DOM takes longer to parse and paint.

  • Avoid deeply nested elements and excessive divs/spans.


11. Avoid Render-Blocking Resources

  • Move non-critical CSS to the bottom or load asynchronously.

  • Inline or defer non-essential scripts.


12. Set Cache-Control Headers

  • Leverage browser caching for static resources.
Cache-Control: public, max-age=31536000

13. Use HTTP/2 or HTTP/3

  • Supports multiplexing, header compression, and faster TLS.

14. Use Efficient Fonts

  • Subset fonts to include only needed characters.

  • Preload key fonts.

<link rel="preload" href="/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin>

💬 Sample Interview Answer

Q: How do you improve the loading speed of HTML pages?

A:
I focus on minimizing HTTP requests, deferring non-critical JavaScript using async or defer, and compressing resources via Gzip or Brotli. I also optimize images, lazy-load media, and use a CDN to serve static assets faster. Inline critical CSS, preload key fonts, and reduce DOM size to improve the Critical Rendering Path. Additionally, I ensure browser caching and leverage HTTP/2 for better resource loading efficiency.

What is the difference between defer and async in script tag ?

The defer and async attributes in the <script> tag are used to control how and when JavaScript files are loaded and executed — a critical part of optimizing page performance.

This is a commonly asked HTML interview question, so let’s break it down clearly and practically.


🧠 The Problem Without defer or async

By default, when a browser encounters a <script src="...">, it:

  1. Stops parsing the HTML.

  2. Downloads the script.

  3. Executes it immediately.

  4. Then resumes parsing HTML.

➡️ This causes render-blocking, delaying page load.


defer Attribute

<script src="script.js" defer></script>

✅ Behavior:

  • Loads the script in parallel with HTML parsing.

  • Executes the script after the HTML document has been completely parsed (but before DOMContentLoaded event).

✅ Use When:

  • You want to ensure the script runs after the DOM is ready.

  • Ideal for scripts that depend on HTML elements being present.

✅ Order:

  • Scripts with defer run in the order they appear in the HTML.

async Attribute

<script src="script.js" async></script>

⚡ Behavior:

  • Loads the script in parallel with HTML parsing.

  • Executes immediately once it's downloaded — even if HTML parsing isn’t finished.

⚡ Use When:

  • The script is independent of DOM or other scripts.

  • Common for analytics, ads, or third-party widgets.

⚡ Order:

  • Not guaranteed to execute in the order they appear.

🆚 Summary Table

AttributeScript LoadingScript ExecutionDOM Parsing Paused?Order Preserved
none (default)ImmediatelyImmediately✅ Yes✅ Yes
asyncIn parallelWhen ready✅ Yes❌ No
deferIn parallelAfter parsing❌ No✅ Yes

💬 Interview Answer Template

Q: What’s the difference between defer and async in the <script> tag?

A:
The defer attribute loads the script in parallel but executes it after the HTML is fully parsed. It ensures the script runs in order and after the DOM is built. The async attribute also loads the script in parallel, but it executes it as soon as it’s downloaded, potentially before the DOM is ready, and doesn't preserve order. defer is ideal for DOM-dependent scripts; async is suitable for independent scripts like analytics.

How do you ensure cross-browser compatibility in HTML?

Ensuring cross-browser compatibility in HTML means making sure your web pages look and behave consistently across different browsers (like Chrome, Firefox, Safari, Edge, etc.) and their various versions.

This is a frequent interview question as it tests your knowledge of web standards, fallbacks, testing tools, and best practices.


🔍 Why Cross-Browser Compatibility Matters

  • Different browsers interpret HTML/CSS/JS slightly differently.

  • Older browsers may not support modern features.

  • Inconsistent rendering leads to a poor user experience.


✅ Key Strategies to Ensure Cross-Browser Compatibility


1. Use Valid, Standards-Compliant HTML

  • Use semantic tags (<header>, <main>, <section>, etc.).

  • Always start with the correct doctype:

      <!DOCTYPE html>
    
  • Validate code using W3C Validator


2. Add Meta Tags for Rendering Behavior

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  • X-UA-Compatible forces latest IE rendering mode.

3. Use Feature Detection (Not Browser Detection)

Use Modernizr or native feature checks:

if ('querySelector' in document) {
  // Safe to use modern features
}

Avoid checking the browser type — it's unreliable.


4. Graceful Degradation & Progressive Enhancement

  • Graceful Degradation: Start with a modern experience, then ensure it fails gracefully on older browsers.

  • Progressive Enhancement: Start with a functional basic version, then layer on enhancements for capable browsers.

Example:

<video controls>
  <source src="movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

5. Test Across Multiple Browsers and Devices

Use tools like:


6. Use CSS Resets or Normalize.css

Different browsers apply different default styles.

  • A reset stylesheet like Normalize.css helps make rendering more consistent:

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
    

7. Avoid Deprecated/Non-Standard Features

Don’t rely on obsolete elements like <center>, <font>, etc.

Instead of:

<font color="red">Text</font>

Use:

<span style="color: red;">Text</span>

8. Use Polyfills for Unsupported Features

  • A polyfill is a JavaScript fallback for features not supported in older browsers.

  • Example: Include the HTML5 Shiv to support HTML5 elements in old IE:

<!--[if lt IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
<![endif]-->

9. Avoid Browser-Specific CSS Prefixes Alone

Use auto-prefixing tools (like PostCSS with Autoprefixer) to add vendor prefixes:

/* Instead of just */
transform: rotate(45deg);

/* Use prefixed */
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);

💬 Sample Interview Answer

Q: How do you ensure cross-browser compatibility in HTML?

A:
I follow standards-compliant HTML and validate it with tools like the W3C Validator. I use meta tags to ensure consistent rendering and avoid deprecated tags. For unsupported features, I use polyfills or fallbacks and test across major browsers using BrowserStack or Chrome DevTools. I also rely on Normalize.css to reset inconsistent default styles and use Autoprefixer to handle vendor prefixes in CSS. For functionality, I use feature detection instead of browser detection and ensure graceful degradation or progressive enhancement where necessary.

What are best practices for writing HTML?

Great interview question! Knowing the best practices for writing HTML shows that you care about code quality, maintainability, performance, accessibility, SEO, and cross-browser compatibility — all critical areas in modern web development.


✅ Best Practices for Writing HTML

Here’s a complete and categorized list of best practices with examples you can mention in interviews:


🧱 1. Use Semantic HTML

Semantic elements describe their meaning, which improves accessibility, SEO, and readability.

Use this:

<header>, <main>, <article>, <section>, <nav>, <footer>, <aside>

Avoid this:

<div id="header">, <div class="content">

🧠 Why: Helps screen readers and search engines understand content structure.


🎯 2. Keep Your HTML Valid and Well-Structured

  • Always start with the correct doctype:

      <!DOCTYPE html>
    
  • Nest tags properly:

      <ul>
        <li>Item</li>
      </ul>
    
  • Use tools like the W3C HTML Validator to catch errors.


📄 3. Use Descriptive and Consistent Naming (IDs, Classes)

✅ Good:

<div class="product-card">...</div>

❌ Bad:

<div class="box123">...</div>

🧠 Why: Improves maintainability and helps teammates or future you understand the code.


🏷️ 4. Use Alt Attributes on Images

<img src="dog.jpg" alt="Golden Retriever playing in the field">

🧠 Why:

  • Helps with accessibility (screen readers).

  • Acts as fallback text if the image doesn't load.

  • Important for SEO.


🔑 5. Use Meta Tags Effectively

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A blog about tech and coding tips.">

🧠 Why: Affects character encoding, responsiveness, and SEO.


🔒 6. Always Escape Special Characters

Use &lt;, &gt;, &amp;, &quot;, &apos; instead of <, >, &, etc., when displaying as content.


♿ 7. Make HTML Accessible (ARIA & Forms)

  • Use label for form inputs:

      <label for="email">Email:</label>
      <input type="email" id="email" name="email">
    
  • Use ARIA roles if needed:

      <div role="dialog">...</div>
    

📐 8. Use Forms Correctly

  • Include action, method, and label for inputs.

  • Group related elements with <fieldset> and <legend>.


🚀 9. Keep It Lean and Performant

  • Avoid inline CSS/JS — separate into files.

  • Minimize unnecessary divs (divitis).

  • Avoid excessive nesting.

  • Use lazy loading for images:

      <img loading="lazy" src="image.jpg" alt="...">
    

🧩 10. Organize Code Logically

  • Keep related elements together.

  • Add meaningful indentation and comments.

Example:

<!-- Navigation -->
<nav>...</nav>

<!-- Main Content -->
<main>...</main>

🧪 11. Test on Different Devices and Browsers

Use tools like:

  • BrowserStack

  • Chrome DevTools (Responsive Design Mode)


🗣 Sample Interview Answer

Q: What are some best practices you follow when writing HTML?

A:
I always use semantic HTML to enhance accessibility and SEO, ensure my markup is valid using the W3C Validator, and follow a consistent and descriptive naming convention for IDs and classes. I include alt attributes on images for accessibility, use appropriate meta tags for encoding and responsiveness, and structure forms properly with labels and fieldsets. I keep the HTML lean, avoid deep nesting or unnecessary elements, and test my pages on multiple browsers and devices. Accessibility, performance, and maintainability are always top priorities.

Difference between embed , object and iframe ?

Great question! <embed>, <object>, and <iframe> are all HTML elements used to embed external content into a webpage — such as multimedia files, documents, or even other web pages — but they differ in purpose, flexibility, and browser support.


🔍 Difference between <embed>, <object>, and <iframe>

Feature<embed><object><iframe>
PurposeEmbeds multimedia like PDFs, SVGs, videos, etc.Embeds almost any external resource; was designed to replace <embed>Embeds an entire HTML document or webpage
Content TypeMultimedia or interactive (e.g., Flash, PDFs, etc.)Multimedia or documents (PDF, Flash, etc.)HTML pages (can include complete websites)
HTML VersionHTML4 & HTML5HTML4 & HTML5HTML4 & HTML5
Fallback Support❌ Limited✅ Allows fallback content❌ No built-in fallback
JavaScript AccessLimitedModerateFull access to iframe's DOM (if same-origin)
Common Use CaseEmbedding video players, PDFsLegacy use for multimedia, plugin contentEmbedding YouTube, maps, login pages, etc.
Attributessrc, type, width, heightdata, type, width, height, namesrc, width, height, name, sandbox

<embed> Example

<embed src="file.pdf" width="600" height="400" type="application/pdf">
  • Simple and lightweight.

  • No fallback content.

  • Primarily used for media.


<object> Example

<object data="file.pdf" type="application/pdf" width="600" height="400">
  Your browser does not support embedded PDFs.
</object>
  • Supports fallback content (Your browser...).

  • Can be used to embed other content types as well (SVG, Flash, etc.).


<iframe> Example

<iframe src="https://example.com" width="800" height="600"></iframe>
  • Embeds a full webpage inside another.

  • Supports sandboxing, resizing, and full interaction if same-origin.

  • Common for maps, third-party widgets, or login forms.


🧠 When to Use Which?

SituationUse
You want to embed a PDF or a video file<embed> or <object>
You want to provide fallback content if the resource fails<object>
You want to embed an entire webpage or interactive app<iframe>
You care about security and sandboxing<iframe> (with sandbox attribute)
You need maximum browser compatibility<object> (has broader support for fallback)

🗣 Sample Interview Answer

Q: What’s the difference between <embed>, <object>, and <iframe>?

A:
<embed> is used to embed external resources like PDFs or videos and is simple but lacks fallback support. <object> is more flexible — it supports various media types and includes fallback content if the media fails to load. <iframe> is specifically for embedding complete HTML documents or web pages, allowing interaction and script access (if same-origin). Each has its own use cases — I usually use <iframe> for web-based embeds like maps or third-party pages, and <object> when I need fallback support for media.

How do you create a responsive image?

Awesome question! Creating responsive images is crucial for ensuring images look good and load efficiently across different devices and screen sizes.


How to Create Responsive Images in HTML

1. Use the srcset and sizes Attributes (Modern Approach)

srcset lets the browser choose the best image resolution based on device pixel ratio and viewport size.

<img 
  src="small.jpg" 
  srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w" 
  sizes="(max-width: 600px) 480px, (max-width: 900px) 800px, 1200px" 
  alt="A beautiful landscape" 
  loading="lazy">
  • srcset — list of images with their widths (w).

  • sizes — tells the browser how much space the image will take at different viewport widths.

  • Browser picks the best image for device and viewport, saving bandwidth.


2. Use CSS with max-width and height: auto

Make images scale down but not exceed their container:

img {
  max-width: 100%;
  height: auto;
  display: block;
}

This keeps the image within the container width while maintaining aspect ratio.


3. Use the <picture> Element for Art Direction

If you want to serve different images depending on viewport or screen density:

<picture>
  <source media="(max-width: 600px)" srcset="small.jpg">
  <source media="(max-width: 1200px)" srcset="medium.jpg">
  <img src="large.jpg" alt="Responsive image example" loading="lazy">
</picture>
  • Allows changing not just resolution but different images depending on screen size.

4. Use loading="lazy" for Performance

<img src="image.jpg" alt="..." loading="lazy">

Lazy loading defers image loading until it’s near the viewport, improving page load times.


Summary:

TechniquePurpose
srcset + sizesResponsive image resolution
CSS max-width + heightImage scales inside container
<picture>Different images by media query
loading="lazy"Improve performance by lazy load

Sample Interview Answer

Q: How do you create a responsive image in HTML?

A: I use the srcset and sizes attributes on the <img> tag to provide multiple image versions, so the browser selects the most appropriate one based on the device and viewport. Additionally, I apply CSS styles like max-width: 100%; height: auto; to ensure the image scales within its container while maintaining aspect ratio. For cases where different images are needed for different screen sizes, I use the <picture> element with media queries. To improve performance, I also add loading="lazy" to defer offscreen image loading.

How does semantic HTML help with SEO?

Great question! Semantic HTML is extremely important for SEO, accessibility, and maintainable code. Let’s break it down:


✅ What is Semantic HTML?

Semantic HTML uses tags that clearly describe their meaning and purpose in the context of the content, such as:

  • <header>, <nav>, <main>, <section>, <article>, <footer>, etc.

These replace generic tags like <div> or <span> when the content has specific meaning.


🧠 How Semantic HTML Helps with SEO

1. Improves Search Engine Understanding

Search engines like Google use bots to crawl and index your site. Semantic HTML helps these bots understand:

  • What the main content is (<main>, <article>)

  • Where the navigation is (<nav>)

  • Where important headings or sections start and end

  • Which content is repeated (e.g., <footer>, <aside>)

Result: Better indexing and ranking in relevant search queries.


2. Enhances Content Structure

Semantic tags create a logical content hierarchy, which helps SEO tools and bots understand content relationships, e.g.:

<article>
  <header><h1>10 Tips for Healthy Living</h1></header>
  <section>
    <h2>Tip 1: Drink Water</h2>
    <p>...</p>
  </section>
</article>

This signals that the <h1> is the main heading and <h2> are subtopics under it.


3. Accessibility (Indirect SEO Benefit)

Screen readers rely on semantic elements to navigate content. A more accessible website leads to:

  • Better user experience

  • Longer engagement times

  • Lower bounce rates

These are positive signals to search engines.


4. Rich Snippets and Schema Integration

Semantic HTML complements structured data (schema.org). Together, they help search engines generate rich results, like:

  • Review stars

  • Event dates

  • Product prices

You can't get those without clear structure and proper use of semantic tags.


🗣 Sample Interview Answer

Q: How does semantic HTML help with SEO?

A: Semantic HTML provides meaningful structure to web content, which helps search engines better understand and index the page. Tags like <article>, <section>, and <nav> tell crawlers what each part of the page represents, improving content discovery and relevance. It also enhances accessibility, which leads to better user experience—something search engines value in their ranking algorithms. Furthermore, semantic HTML makes it easier to integrate structured data, enabling rich search results.

What are ARIA (Accessible Rich Internet Applications) attributes?

Excellent question — ARIA attributes are crucial for building accessible web applications, especially when using custom components that aren’t inherently accessible.


🔍 What is ARIA?

ARIA stands for Accessible Rich Internet Applications. It's a set of attributes that can be added to HTML elements to improve accessibility for users who rely on assistive technologies like screen readers.


✅ Why is ARIA Needed?

HTML has built-in accessibility features (like <button>, <input>, etc.), but custom elements made with <div> or <span> have no semantic meaning.

ARIA attributes bridge this gap by providing:

  • Roles: Describe what an element is

  • States: Describe its current condition (e.g. expanded/collapsed)

  • Properties: Describe its relationships with other elements


💡 Common ARIA Attributes

AttributePurposeExample
roleDefines what the element is (e.g., button, dialog)role="button"
aria-labelProvides a label when there is no visible textaria-label="Close menu"
aria-labelledbyReferences another element's ID for labelingaria-labelledby="heading-id"
aria-hiddenHides content from screen readersaria-hidden="true"
aria-expandedIndicates whether an element is expanded or collapsedaria-expanded="false"
aria-controlsPoints to the ID of the element being controlledaria-controls="menu-id"
aria-liveAnnounces dynamic content changesaria-live="polite"
aria-pressedUsed with toggle buttons to show statearia-pressed="true"

🧠 Example: Accessible Custom Toggle Button

<div 
  role="button" 
  aria-pressed="false" 
  aria-label="Toggle sidebar"
  tabindex="0"
  onclick="toggleSidebar()"
></div>
  • role="button": tells screen readers it's a button

  • aria-pressed: communicates toggle state

  • aria-label: gives an accessible name

  • tabindex="0": makes it focusable via keyboard


🚫 When NOT to Use ARIA

Don’t use ARIA when you can use native HTML” — W3C

Avoid using ARIA if a native HTML element already provides the needed behavior. For example, prefer:

<button>Submit</button>

Over:

<div role="button">Submit</div>

🗣 Sample Interview Answer

Q: What are ARIA attributes?

A: ARIA stands for Accessible Rich Internet Applications. It’s a set of attributes that enhance accessibility for users relying on screen readers or other assistive technologies. ARIA is especially useful when building custom UI components where native HTML semantics are missing. Attributes like role, aria-label, and aria-expanded provide context, state, and relationships, helping assistive tools interpret and interact with the interface properly. However, best practice is to use native HTML elements whenever possible, and rely on ARIA only when necessary.

How would you make a website accessible?

That’s an essential and frequently asked interview question — and answering it well shows that you care about all users. Let’s go through it step-by-step.


✅ What Does “Accessible Website” Mean?

An accessible website ensures that everyone, including people with disabilities (visual, auditory, motor, cognitive), can navigate, understand, and interact with your content.


🧠 Key Principles: POUR

Accessibility is guided by four principles (W3C WCAG):

PrincipleMeaning
PerceivableUsers must be able to perceive the content (text alternatives, captions, color contrast)
OperableUsers must be able to operate the interface (keyboard navigation, focus indicators)
UnderstandableContent should be readable and predictable
RobustWorks across different browsers and assistive tech

🚀 How to Make a Website Accessible

1. Use Semantic HTML

Use proper HTML tags to convey meaning:

  • Use headings (<h1> to <h6>) in correct order

  • Use <nav>, <main>, <article>, <section>, <footer>, etc.

  • Avoid using <div>s for everything

Why? Screen readers can better navigate the structure.


2. Keyboard Accessibility

  • Ensure all functionality works with keyboard only (Tab, Enter, Space, etc.)

  • Use tabindex wisely

  • Provide visible focus styles (:focus)

Why? Many users can’t use a mouse.


3. Use ARIA Attributes (When Needed)

When using custom UI components, use ARIA:

  • role="button" for custom buttons

  • aria-expanded, aria-hidden, aria-live, etc.

  • aria-label or aria-labelledby for screen reader labels

🚫 Avoid ARIA if native HTML does the job.


4. Provide Text Alternatives

  • Use alt on images: <img src="logo.png" alt="Company Logo">

  • Use transcripts for audio

  • Use captions for videos


5. Ensure Color Contrast

Use tools (like WebAIM Contrast Checker) to ensure:

  • Text color has enough contrast against background

  • Avoid color-only indicators (e.g., "red means error")


6. Label Form Elements

  • Use <label for="id"> or wrap the input

  • Associate fields with descriptions using aria-describedby

Example:

<label for="email">Email</label>
<input type="email" id="email" aria-describedby="emailHelp">
<small id="emailHelp">We'll never share your email.</small>

Allow keyboard users to skip repetitive content like navbars:

<a href="#main-content" class="skip-link">Skip to main content</a>

8. Responsive and Scalable

  • Make layout responsive

  • Use em, rem units so users can zoom text


9. Test with Screen Readers and Tools

  • Try with NVDA, VoiceOver, or JAWS

  • Use tools like:

    • Lighthouse (Chrome DevTools)

    • WAVE

    • axe DevTools


🗣 Sample Interview Answer

Q: How would you make a website accessible?

A: I follow accessibility best practices like using semantic HTML, ensuring keyboard navigability, and providing alternative text for non-text content. I label all form fields properly and ensure sufficient color contrast. Where custom components are used, I enhance accessibility with ARIA attributes. I also test with screen readers and tools like Lighthouse or axe. Additionally, I use techniques like skip links and responsive design to improve usability for everyone. My goal is to meet WCAG guidelines and create an inclusive experience.

Why is using headings (h1 to h6) properly important ?

Great question — using headings (<h1> to <h6>) properly is critical for accessibility, SEO, and content structure. It’s one of the first things interviewers look for when assessing your understanding of semantic HTML and good practices.


✅ Why Proper Use of Headings Matters

1. Semantic Structure & Content Hierarchy

Headings establish a visual and logical outline of your content, like a table of contents:

<h1>Main Title</h1>
  <h2>Section 1</h2>
    <h3>Subsection 1.1</h3>
  <h2>Section 2</h2>
  • <h1> is usually the main title of the page.

  • <h2> to <h6> are used to nest content logically.

✅ This helps both humans and machines understand the organization of your page.


2. Accessibility

Screen readers often use headings as navigation shortcuts. For example:

  • Users can press a key (like H in NVDA) to jump between headings

  • Proper nesting (e.g., no skipping from <h1> to <h4>) improves usability

✅ Headings give context and help screen reader users skim and navigate efficiently.


3. SEO (Search Engine Optimization)

Search engines use headings to understand:

  • What the page is about (<h1>)

  • Key topics and subtopics (<h2>, <h3>, etc.)

✅ Using relevant keywords in headings boosts discoverability and ranking.


4. Maintainability & Readability

Proper headings make code and content easier to:

  • Read

  • Maintain

  • Collaborate on

✅ Developers and content editors can scan the document quickly.


❌ Common Mistakes to Avoid

MistakeWhy it's bad
Skipping heading levels (h1h4)Breaks logical structure
Using headings for styling onlyMisleads assistive tech
Having multiple <h1>s on one page (without good reason)Confuses hierarchy (note: HTML5 allows it inside separate <section>s, but use wisely)
Not using any headingsBad for SEO and accessibility

✅ Best Practices

  • Always use only one <h1> for the main page title.

  • Follow a logical order: <h1><h2><h3> etc.

  • Avoid skipping levels unless necessary.

  • Use CSS for styling — not heading tags.


🗣 Sample Interview Answer

Q: Why is it important to use headings properly in HTML?

A: Properly using <h1> to <h6> establishes a clear content hierarchy and improves both accessibility and SEO. Screen readers rely on headings for navigation, and search engines use them to determine page structure and relevance. Using them semantically also helps developers maintain and understand the content better. I always use a single <h1> for the main title, then nest sections using <h2> to <h6> in logical order.

What is localStorage vs sessionStorage?

Great question — especially for frontend or full-stack interviews!

Both localStorage and sessionStorage are part of the Web Storage API, introduced in HTML5. They allow you to store key–value pairs in the browser, but with important differences in scope, persistence, and usage.


✅ Quick Comparison: localStorage vs sessionStorage

FeaturelocalStoragesessionStorage
PersistencePersistent (until manually cleared)Temporary (cleared when tab/window closes)
ScopeShared across tabs/windows of same originUnique to each tab/window
Storage Size~5–10 MB (browser-dependent)~5 MB (browser-dependent)
AccessibilityAccessible by any script on same originOnly accessible in the tab that created it
Use CasesUser preferences, theme, auth tokensForm data in a single session, multi-step forms
ExpiryNever (must be explicitly deleted)Automatically expires on session end

🔹 Syntax (Both Work the Same)

// Set an item
localStorage.setItem("username", "siddhanth");
sessionStorage.setItem("sessionId", "abc123");

// Get an item
const user = localStorage.getItem("username");
const session = sessionStorage.getItem("sessionId");

// Remove an item
localStorage.removeItem("username");

// Clear all items
sessionStorage.clear();

📌 Example Use Case

localStorage Example:

// Save dark mode preference
localStorage.setItem("theme", "dark");

sessionStorage Example:

// Save step 1 form data during a multi-step form
sessionStorage.setItem("step1Data", JSON.stringify({ name: "John" }));

⚠️ Notes

  • Only stores strings — use JSON.stringify() and JSON.parse() for objects.

  • Both are synchronous — avoid storing too much data.

  • Not suitable for sensitive information (no encryption).

  • Not shared across different origins (protocol + domain + port).


🧠 Sample Interview Answer

Q: What's the difference between localStorage and sessionStorage?

A: Both are part of the Web Storage API and allow key-value pair storage in the browser. The key difference is that localStorage persists data even after the browser is closed, while sessionStorage clears data when the tab or window is closed. Also, localStorage is shared across tabs of the same origin, but sessionStorage is isolated per tab. I typically use localStorage for long-term preferences and tokens, and sessionStorage for temporary data like step-by-step form inputs.

What is the purpose of the <canvas> element?

The <canvas> element in HTML5 provides a drawing surface that can be used to render graphics — such as shapes, images, charts, games, or even animations — using JavaScript.

It acts like a blank area on the web page where you draw things programmatically via the Canvas API.


✅ Purpose of <canvas>

  • Dynamic rendering of 2D (and with WebGL, 3D) graphics

  • Enables building:

    • Games

    • Data visualizations (e.g., charts, graphs)

    • Custom image editors

    • Particle animations

    • Video processing overlays

    • Real-time drawing apps


🔧 Basic Syntax

<canvas id="myCanvas" width="300" height="150">
  Your browser does not support the canvas element.
</canvas>

Then in JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a red rectangle
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 75);

🧠 Key Points

FeatureExplanation
Not semanticUnlike <svg>, canvas has no built-in semantics
JavaScript requiredYou need JS to draw/render content
Pixel-basedDrawing happens pixel-by-pixel
StatelessDoesn’t retain object info (you redraw manually)
Use getContext()Typically 2d, but webgl and webgl2 are also valid

🆚 Canvas vs SVG

Aspect<canvas><svg>
TypeRaster (pixel-based)Vector (shape-based)
PerformanceBetter for thousands of objects or animationsBetter for static or fewer elements
AccessibilityNeeds extra effortInherently more accessible
InteractivityRequires manual hit detectionBuilt-in (can attach events)

🧠 Sample Interview Answer

Q: What is the purpose of the <canvas> element in HTML5?

A: The <canvas> element is used to draw graphics via JavaScript, such as shapes, charts, games, or animations. It provides a pixel-based drawing surface and is highly useful for rendering dynamic, custom graphics on the fly. Unlike SVG, canvas doesn't retain drawing information — it simply paints pixels. It’s well-suited for scenarios like game development, custom image editing, or particle systems where real-time rendering is needed.

What is the <template> tag and when it is used ?

Great question — the <template> tag is an advanced yet super useful feature in HTML for modern web development, especially when dealing with dynamic or reusable UI components.


✅ What is the <template> Tag?

The <template> tag is a container for HTML that you want to prepare but not render immediately when the page loads.

  • The contents inside <template> are not displayed in the DOM when the page loads.

  • It's meant to be cloned and injected into the DOM using JavaScript.


📌 Purpose

  • To define HTML chunks that should be reused dynamically (e.g., cards, list items).

  • Keeps the DOM clean and improves performance by delaying rendering.

  • Often used in:

    • Component libraries

    • Client-side rendering

    • Shadow DOM / Web Components

    • Dynamic list generation (e.g., <ul><li>...</li></ul> with JS)


🧪 Example

<template id="user-card">
  <div class="user">
    <h3 class="name"></h3>
    <p class="email"></p>
  </div>
</template>

<div id="output"></div>

<script>
  const users = [
    { name: "Alice", email: "alice@example.com" },
    { name: "Bob", email: "bob@example.com" }
  ];

  const container = document.getElementById("output");
  const template = document.getElementById("user-card");

  users.forEach(user => {
    const clone = template.content.cloneNode(true);
    clone.querySelector(".name").textContent = user.name;
    clone.querySelector(".email").textContent = user.email;
    container.appendChild(clone);
  });
</script>

🔍 Output:

This dynamically renders a card for each user from the <template> without writing HTML manually or polluting the DOM beforehand.


🧠 Key Points

FeatureDescription
Not renderedContent is inert until you use JS
Ideal forReusable UI fragments (cards, modals, etc.)
CloningUse template.content.cloneNode(true)
SafeScripts inside <template> do not run

🧠 Sample Interview Answer

Q: What is the <template> tag and when would you use it?

A: The <template> tag is used to define reusable HTML fragments that are not rendered immediately in the DOM. The content inside remains inert until it is cloned using JavaScript. It's useful for rendering dynamic lists, cards, or components when data is loaded asynchronously. This allows for clean, efficient, and dynamic DOM manipulation without bloating the initial DOM structure.

How does HTML5 Geolocation API work?

The HTML5 Geolocation API allows web applications to get the geographic location of the user (latitude, longitude, and more) using their device’s capabilities (like GPS, Wi-Fi, IP address, etc.).


✅ How It Works (Step-by-Step)

  1. User grants permission:
    The browser asks the user if they want to share their location.

  2. Browser gets location data:
    The browser determines your position using:

    • GPS (mobile)

    • Wi-Fi or Bluetooth positioning

    • Cell tower triangulation

    • IP address (least accurate)

  3. Callback functions handle result:

    • If successful: it returns a position object with coordinates.

    • If failed/denied: an error is returned.


🔧 Basic Syntax

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    successCallback,     // Required: on success
    errorCallback,       // Optional: on error
    options              // Optional: configuration
  );
} else {
  console.log("Geolocation is not supported by this browser.");
}

📍 Example

navigator.geolocation.getCurrentPosition(
  function (position) {
    console.log("Latitude: " + position.coords.latitude);
    console.log("Longitude: " + position.coords.longitude);
  },
  function (error) {
    console.warn("ERROR(" + error.code + "): " + error.message);
  }
);

⚙️ Options Object (Optional 3rd Argument)

{
  enableHighAccuracy: true, // GPS-level precision
  timeout: 5000,            // Time in ms to wait
  maximumAge: 0             // Don't use cached location
}

📦 Position Object Structure

{
  coords: {
    latitude: 40.7128,
    longitude: -74.0060,
    altitude: null,
    accuracy: 25,
    altitudeAccuracy: null,
    heading: null,
    speed: null
  },
  timestamp: 1620000000000
}

⚠️ Permissions & Security

  • Only works on HTTPS (or localhost).

  • Requires user consent — cannot silently access location.

  • Browsers typically display a location prompt at the top of the page.


🧠 Sample Interview Answer

Q: How does the HTML5 Geolocation API work?

A: The Geolocation API enables web applications to access the user’s physical location with their permission. It uses the device's GPS, Wi-Fi, IP address, or cellular data to determine position. The navigator.geolocation.getCurrentPosition() method is used to fetch the location asynchronously. It requires the user’s consent and only works over HTTPS due to privacy concerns. If granted, it returns an object containing coordinates like latitude, longitude, accuracy, and more.

1
Subscribe to my newsletter

Read articles from Siddhanth Chauhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Siddhanth Chauhan
Siddhanth Chauhan