• Testing Basics
  • Home
  • /
  • Learning Hub
  • /
  • Top 90+ HTML Interview Questions and Answers in 2024
  • -
  • July 24 2024

Top 90+ HTML Interview Questions and Answers in 2024

Discover essential HTML interview questions for freshers, intermediates, and experienced professionals to prepare and excel in your web development career.

  • General Interview QuestionsArrow
  • CI/CD Tools Interview QuestionsArrow
  • Testing Types Interview QuestionsArrow
  • Testing Framework Interview QuestionsArrow
  • Programming Languages Interview QuestionsArrow
  • Development Framework Interview QuestionsArrow
  • Automation Tool Interview QuestionsArrow

OVERVIEW

HTML is the core of web development, using various tags and elements. These tags and properties can be combined to create visually appealing and engaging web pages. HTML is the foundation for adding styling and website functionality through CSS and JavaScript.

This guide provides a collection of the top 90+ HTML interview questions and answers, covering topics from basic HTML concepts to advanced topics.

Note

Download HTML Interview Questions

Note : We have compiled all HTML Interview Question for you in a template format. Feel free to comment on it. Check it out now!!

HTML Interview Questions for Freshers

This section covers HTML interview questions for freshers, such as basic tags, the structure of an HTML document, and creating links and lists.

1. What Is HTML?

HTML stands for Hypertext Markup Language and is used to create web pages. It combines Hypertext, which defines links between web pages, and Markup language, which defines the structure of text documents within tags.

Example:

<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
  </head>
  <body>
    <h2>Learning Hub</h2>
    <p>Top 90+ HTML Interview Questions and Answers in 2024 </p>
  </body>
</html>

2. What Is the Difference Between HTML and XHTML?

HTML and XHTML are markup languages designed for web page creation and display. HTML offers a more lenient syntax, whereas XHTML follows a stricter syntax that complies with XML rules.

3. What Are the Building Blocks of an HTML Document?

HTML document is built using a combination of these three building blocks:

  • Tags: Define the structure and semantics of the content.
  • Attributes: Provide additional information or properties to the tags.
  • Elements: Consist of tags, attributes, and content, forming the complete structure of the document.

4. What Is !DOCTYPE?

The !DOCTYPE is an instruction used by web browsers to determine the version of HTML the website is written in. This helps browsers understand how the document should be interpreted, simplifying the rendering process. The !DOCTYPE is neither an element nor a tag. It should be placed at the very top of the document, contain no content, and do not require a closing tag.

5. What Are HTML Tags?

HTML tags are the building blocks of any web page, which are keywords that structure web pages in different formats. These tags are paired with opening and closing tags, although some are standalone and do not require closing.

The basic structure of an HTML tag is as follows:

<tagname> Content... </tagname>

6. What Are HTML Attributes?

HTML attributes provide additional information about elements within an HTML document. Every HTML element can have attributes, which are always defined in the start tag. Attributes use a name/value pair format, where the attribute name defines the property and the value provides specific details. These attributes affect how content is displayed and interacted with on web pages.

7. What Is the Difference Between <strong> , and <b> tags and, <em> and <i> Tags?

Here are the difference between <strong>, and <b> tags and <em> and <i> tags:

<strong> and <b> tags:

  • <strong>: This tag indicates that the enclosed text has strong importance or emphasis in the content context. It conveys semantic meaning, suggesting that the text is of higher relevance or significance.
  • <b>: This tag makes the enclosed text bold or visually emphasized. It conveys no semantic meaning; it is a purely presentational tag.

<em> and <i> tags:

  • <em>: This tag indicates that the enclosed text should be stressed or emphasized from the surrounding text. It conveys semantic meaning, suggesting that the text should be read with stress or emphasis.
  • <i>: This tag makes the enclosed text appear in italics. Like the <b> tag, it is purely presentational and conveys no semantic meaning.
...

8. How Can You Add an Image in HTML?

We can use an HTML tag called <img> to add an image to a web page. This tag tells the browser that you want to display a picture.

Inside the <img> tag, you need to provide the source or location of the image file. You do this by using the src attribute.

Syntax:

<img src="image.jpg" alt="Description of the image">

9. Why Is the alt Attribute Used in HTML Images?

The alt attribute is used to specify alternate text for an image. This is helpful when the image cannot be displayed and provides alternative information for the image.

10. How to Comment in HTML?

In HTML, you can add comments between <!-- ... --> tags. The start tag includes an exclamation mark (!), but the end tag does not.

There are two types of comments in HTML:

  • Single-line comment: This comment adds a single line within the HTML code. The syntax is as follows:
  • <!-- Single-line comment -->
  • Multi-line comment: Multi-line comments are used to add comments that span across multiple lines. The syntax is as follows:
  • 
    <!--
      Multi-line
      comment 
    -->
    
    

11. How Do You Define Headings in HTML?

HTML headings are defined using the <h1> to <h6> tags.

  • <h1> defines the most important heading with the biggest font size.
  • <h6> defines the least important heading and has the smallest font size.

Example:

<h1>Learning Hub</h1>
<h2>Learning Hub</h2>
<h3>Learning Hub</h3>
<h4>Learning Hub</h4>
<h5>Learning Hub</h5>
<h6>Learning Hub</h6>

12. How to Create a Table in HTML?

To create a basic table in HTML:

  • Use the <table> tag to define the table.
  • Create rows with the <tr> (table row) tag.
  • Define headers using <th> (table header) tags.
  • Add data cells using <td> (table data) tags.

Example:

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jim</td>
    <td>3</td>
  </tr>
  <tr>
    <td>Jam</td>
    <td>2</td>
  </tr>
</table>

This structure creates a 2x2 table with headers for Name and Age, followed by two rows of data.

13. What Are the Different Types of Lists in HTML?

HTML lists are used to organize information into a structured format. They can contain various types of content, such as paragraphs or images. There are three main types of lists:

  • Ordered lists (<ol>): These lists are numbered.
  • Unordered lists (<ul>): These lists use bullets.
  • Description lists (<dl>): These lists are used for terms and their descriptions.

Example:

<!-- Unordered list -->
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<!-- Ordered list -->
<ol>
  <li>First Item</li>
  <li>Second Item</li>
  <li>Third Item</li>
</ol>

<!-- Description list -->
<dl> 
<dt>HTML</dt> 
<dd>Hypertext Markup Language</dd> 
<dt>CSS</dt> 
<dd>Cascading Style Sheets</dd> 
</dl>

14. How to Create a Link in HTML?

In HTML, links are used to connect web pages or HTML documents. To create a link, you can use the anchor tag (<a>) with the href attribute specifying the URL or destination.

<a href="https://www.lambdatest.com/learning-hub/">Learning Hub</a>

15. What Is the Use of the Target Attribute in the <link> Tag?

The target attribute in the <a> tag specifies where the linked document should open. Some common values are:

  • _self (default): Opens the linked document in the same window/tab.
  • _blank: Opens the linked document in a new window or tab.
  • _parent: Opens the linked document in the parent frame (for iframes).
  • _top: Opens the linked document in the full body of the window.

16. How Many Ways Can You Display HTML Elements?

HTML elements can be displayed in various ways, including block, inline, inline-block, and none. The display property is used to specify how an element should be rendered on the page.

17. What Is the Difference Between Block and Inline Elements?

Here are the primary differences between block elements and inline elements:

Characteristics Block-level Elements Inline-level Elements
New Line Starts on a new line. Does not start on a new line.
Width Takes up the full available width. Takes up the width of its content only.
Height Can have a height set. Height is determined by its content.
Margins/Padding Can have margins/padding on all sides. Can have left/right margins/padding, but not top/bottom.
Alignment Can be aligned using text-align and margin properties. Can be aligned using the vertical-align property.

18. Is It Possible to Change an Inline Element Into a Block-Level Element?

Yes, it is possible to change the display behavior of an HTML element using CSS. You can use the display property to change an inline element into a block-level element or vice versa.

/* Change an inline element to block-level */
span {
  display: block;
}

/* Change a block-level element to inline */
div {
  display: inline;
}

19. How to Align Text in HTML?

Text alignment in HTML is achieved using CSS. The text-align property is used to horizontally align text within an element.

/* Align text to the left */
p {
  text-align: left;
}

/* Align text to the right */
h1 {
  text-align: right;
}

/* Align text in the center */
div {
  text-align: center;
}

20. How to Change Text Color in HTML?

You can use the color property in CSS to change the color of text in HTML.

/* Change text color to blue*/
p {
  color:blue;
}

21. How to Change Font Color in HTML?

Changing the font color in HTML is the same as changing the text color, which is done using the color property in CSS.

/* Change font color to green */
body {
  color: green;
}

22. How to Change the Background Color in HTML?

To change the background color of an HTML element, you can use the background-color property in CSS.


/* Change body background color to gray */
body {
  background-color: gray;
}

/* Change div background color to white*/
div {
  background-color: white;
}

23. How to Change Font Style in HTML?

To change the font style in HTML, you can use various CSS properties:

  • font-family: Specifies the font family to be used.
  • font-size: Sets the font size.
  • font-style: Specifies whether the text should be normal, italic, or oblique.
  • font-weight: Sets the boldness of the text (normal, bold, or a numeric value).

Example:

/* Change font family, size, and style */
h1 {
  font-family: sans-serif;
  font-size: 24px;
  font-style: italic;
  font-weight: bold;
}

24. What Is DOM?

The DOM, or Document Object Model, is a programming interface that represents structured documents such as HTML and XML as a tree of objects. It defines how to access, manipulate, and modify document elements using scripting languages like JavaScript.

25. What’s the Connection Between JavaScript and DOM?

The Document Object Model provides a tree-like representation of HTML documents. JavaScript allows for accessing and modifying the DOM, facilitating alterations to the structure or content within an HTML document.

26. Can You Describe Common Issues That Arise During DOM Manipulation?

One common issue is the slowness of DOM updates, which occur every time the page loads and can consume substantial time and processing resources. Another common issue is the complexity of working with the DOM, which is particularly challenging for those who lack proficiency in HTML and CSS. This complexity can hinder the effective manipulation of the DOM to achieve desired results.

27. How to Create a Form in HTML?

To create a form in HTML, you can use the <form> element. Inside the <form> element, you can include various form controls like input fields, dropdowns, checkboxes, radio buttons, and more.

Example:

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

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

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

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

The action attribute in the <form> tag specifies the URL or server-side script where the form data will be submitted.

The method attribute specifies the HTTP method used to submit the form data.

28. How to Link CSS to HTML?

There are three ways to link CSS to an HTML document:

  • Inline CSS: CSS styles are applied directly to an HTML element using the style attribute.
  • <p style="color: pink; font-weight: bold;">This text is pink and bold.</p>
  • Internal CSS: CSS styles are defined within the <style> element in the <head> section of the HTML document.
  • <!DOCTYPE html>
    <html>
    <head>
      <style>
        p {
          color: red;
          font-weight: bold;
        }
      </style>
    </head>
    <body>
      <p>This text is red and bold.</p>
    </body>
    </html>
  • External CSS: CSS styles are defined in a separate .css file, and the HTML document links to that file using the <link> element in the <head> section.
  • <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet"

29. What Are the Benefits of Collapsing White Space?

Below are the benefits of collapsing white space:

  • When writing HTML, collapsing white spaces helps make the code more understandable for users.
  • Collapsing white spaces reduces the amount of data transferred between the server and client by removing unnecessary bytes.
  • If extra white spaces are accidentally left in the code, the browser will ignore them and render the UI correctly.

30. How to Use a <div> Tag in HTML to Divide the Page?

The <div> (division) tag is a block-level element in HTML commonly used to divide a web page into sections or create layout structures. It acts as a container for other HTML elements and can be styled using CSS.

Here's an example of how to use <div> tags to divide a page:

<!DOCTYPE html>
<html>
<head>
  <title>Page Layout</title>
  <style>
    .header, .nav, .content{
      padding: 20px;
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Website Header</h1>
  </div>
  <div class="nav">
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </div>
  <div class="content">
    <h2>Content Section</h2>
    </div>
</body>
</html>

31. How to Add a Scroll Bar in HTML?

To add a scroll bar in HTML, you can use CSS to control the overflow behavior of an element. When the content inside an element exceeds its specified height or width, a scroll bar will automatically appear.

32. Which HTML Tags Are Used to Separate a Section of Text?

The tags used to separate sections of text in HTML are:

  • <br>: The <br> tag is commonly used to insert line breaks within text, allowing content to flow onto the next line.
  • <p>: Content wrapped in the <p> tag is presented as a new paragraph, organizing text into coherent blocks.
  • <blockquote>: This tag defines sizable quoted sections within the content.

33. Is It Possible to Include One CSS File in Another?

Yes, including one CSS file in another is possible, and this process can be repeated multiple times. Additionally, you can import multiple CSS files into the main HTML file or the primary CSS file using the @import keyword.

34. How to Add a Footer in HTML?

To add a footer in HTML, you can use a <footer> element or a <div> element with an appropriate class or ID. The footer is placed at the bottom of the web page and can contain various elements like copyright information, navigation links, or other relevant content.

Example of how to add a footer using a <footer> element:

<!DOCTYPE html>
<html>
<head>
  <title>Website with Footer</title>
  <style>
    footer {
      background-color: #333;
      color: #fff;
      padding: 20px;
      text-align: center;
    }
  </style>
</head>
<body>
  <!-- Your website content goes here -->

  <footer>
    <p>&copy; 2024 Your Website. All rights reserved.</p>
    <nav>
      <ul>
        <li><a href="#">Privacy Policy</a></li>
        <li><a href="#">Terms of Use</a></li>
        <li><a href="#">Contact Us</a></li>
      </ul>
    </nav>
  </footer>
</body>
</html>
Note

Download HTML Interview Questions

Note : We have compiled all HTML Interview Question for you in a template format. Feel free to comment on it. Check it out now!!

HTML Interview Questions for Intermediate

Here are the HTML interview questions for intermediate professionals that delve into more complex topics like semantic HTML, forms, multimedia elements, and the differences between block-level and inline elements.

1. What Is XML Parsing?

XML parsing is the conversion of an XML document into a format that is understandable by computers. It involves creating a tree or graph structure for computational processing.

2. What Are the Various Kinds of Nodes Present in the DOM?

Below are the various kinds of nodes present in the DOM:

  • Element nodes: Element nodes are the most common type of node in the DOM. They represent HTML tags such as <div>, <p>, and <a>. Element nodes can contain other nodes as children, allowing for the creation of complex, nested structures.
  • Attribute nodes: Attribute nodes store additional information about elements. They are not part of the main DOM tree but are associated with element nodes. Attribute nodes hold data such as an element's id, class, or custom data attributes.
  • Text nodes: Text nodes contain the actual textual content of an element. These nodes represent the words, numbers, and spaces users see on a web page. Text nodes are always leaf nodes, meaning they cannot have their child nodes.
  • Comment nodes: Comment nodes store comments that developers add to the HTML document. While not visible on the rendered page, these nodes are important in code documentation and organization.

3. How to Add and Remove Elements From the DOM?

To add an element to the Document Object Model, you must first create the element. After creation, you can append it to the desired location within the DOM. To remove an element from the DOM, you first locate the element you want to remove and then execute its remove() method.

4. What Is the Best Approach to Create a New HTML Page Dynamically?

The best approach for dynamically creating a new HTML page is to use the document.createElement() method. This method enables you to generate any desired element, including an entire HTML page. Once the element is created, it can be attached to the current document using the appendChild() method.

6. What Is Semantic HTML?

Semantic HTML refers to coding practices that use HTML tags to convey the meaning of content on a web page rather than focusing solely on its visual presentation. This approach makes it easier for search engines and other software to interpret and process the page effectively.

7. How to Create a Form in HTML?

To create a form in HTML, use the <form> element. Inside this element, add various input fields using different HTML elements such as <input>, <textarea>, <select>, and more.

Example of a basic form with a text input field and a submit button:

<form>
  Name: <input type="text"><br>
  <input type="submit" value="Submit">
</form>

8. What Is the Difference Between <div> and <span> Tag?

The <div> and <span> tags are both HTML elements used for grouping and structuring content, but they have different objectives.

<div> is a block-level element, which starts on a new line and takes up the full width available by default. It is commonly used for creating larger groupings or sections of content, such as headers, footers, sidebars, and layout containers.

<span>, on the other hand, is an inline-level element, which means it does not start on a new line and only takes up as much width as its content requires. It is used for styling or grouping smaller pieces of text within a line, such as highlighting a word or phrase or applying specific formatting to a part of a sentence.

Below are some differences between <div> and <span>:

  • <div> elements are block-level, while <span> elements are inline-level.
  • <div> elements start on a new line and take up the full available width by default, while <span> elements stay within the line and only occupy the space needed for their content.
  • Multiple <div> elements will stack vertically one after the other, while multiple <span> elements will continue on the same line.
  • <div> elements are often used as containers for applying styles and layout to larger content sections, while <span> elements apply styles to smaller portions of text.

9. What Is the Difference Between Classes and ID?

Both classes and IDs are used in HTML to identify and target elements for styling and manipulation with CSS and JavaScript. However, they have some differences:

Classes:

  • Classes are represented by the class attribute in HTML elements.
  • An element can have multiple classes assigned to it.
  • Classes are intended to group elements with similar characteristics or styles.
  • Classes are used to target and style multiple elements at once.
  • Classes are defined using the dot (.) notation in CSS, for example, .class-name.

IDs:

  • IDs are represented by the id attribute in HTML elements.
  • An element can have only one unique ID assigned to it within a single HTML document.
  • IDs are intended to identify a specific, unique element on the page.
  • IDs are often used for JavaScript manipulation or as CSS anchors.
  • IDs are defined using the CSS hash (#) notation, for example, #id-name.

Here are some differences between classes and IDs:

Aspects Classes IDs
Usage frequency Can be used multiple times Should be unique per page
Specificity Lower specificity Higher specificity
Purpose Grouping similar elements Identifying unique elements
Multiple values Can have multiple classes Can only have one ID
Performance Slightly slower Slightly faster
Best for Reusable styles Unique styles or JavaScript hooks

10. How to Add a Video to an HTML Document?

To add a video to an HTML document, use the <video> element. It allows for the inclusion of one or more video sources using the <source> tag. It supports MP4, WebM, and Ogg formats across all modern browsers except for Safari, which does not support the Ogg video format.

Syntax:

<video>
<source src=”file_name” type=”video_file_type”>
</video>

Let’s understand this with an example:

<!DOCTYPE html>
<html>
<body style="text-align: center">
    <h2>How to add video in HTML</h2>
    <video width="600px" 
           height="500px" 
           controls="controls">
        <source src= "https://www.lambdatest.com/resources/videos/lambdatest-smart-ui-testing.mp4"  type="video/mp4" />
    </video>
</body>
</html>

11. How to Embed Audio in an HTML Document?

To embed audio in an HTML document, use the <audio> element. Before HTML5, audio could not be added directly to web pages during the Internet Explorer era, so web plugins like Flash were used to play audio. With the release of HTML5, this became possible.

The <audio> tag in HTML5 supports three audio formats—MP3, WAV, and Ogg—across major browsers like Chrome, Firefox, Safari, Opera, and Edge. However, the Safari browser does not support the Ogg audio format.

Syntax:

<video>
<source src=”file_name” type=”audio_file_type”>
</video>

Let’s understand this with an example:

<!DOCTYPE html>
<html>
<body>
    <h2>Listen to Audio</h2>
    <audio controls>
        <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
</body>
</html>

12. What Is SVG in HTML?

Scalable Vector Graphics (SVG) is an XML-based vector image format for creating two-dimensional graphics. SVG images can be embedded directly into HTML documents using the <svg> element.

13. How Do You Create a Responsive Image in HTML?

There are three methods to create responsive images in HTML:

  • Art direction: As an alternative to the srcset and sizes attributes, the <picture> element in HTML lets you set breakpoints. These are critical points where the page design changes to improve user experience. This method, art-directing images, lets you display different images at various breakpoints.
  • Resolution switching: Resolution switching uses the srcset and sizes attributes to provide multiple versions of an image, allowing browsers to choose the most appropriate one based on device resolution and viewport size.
  • Image format switching: This technique adapts image formats based on browser support, using the <picture> element to provide fallback options. It's particularly useful for serving modern, efficient formats to support browsers while ensuring compatibility with older ones.

14. How Can We Create a Nested Web Page in HTML?

A nested web page refers to embedding one web page's content within another from a different domain. This technique allows you to display external content directly within your web page.

There are two primary methods to achieve this in HTML:

  • Using the <iframe> tag: The <iframe> tag creates a rectangular region within your document where a separate web page can be displayed, complete with scrollbars and borders if needed.
  • Syntax:

    <iframe src=”URL”></iframe>

    Here's an example:

    <iframe src="https://www.lambdatest.com/learning-hub/"
    			height="400px" width="900px">
    	</iframe>
  • Using the <embed> tag: The <embed> tag is traditionally used for embedding multimedia content but can also be used to embed raw HTML content, including entire web pages.
  • Syntax:

    <embed src=”URL” type=”text/html” />

    Here's an example:

    <embed src="https://www.lambdatest.com/learning-hub/"
    		type="text/html" />

15. What Tags Can Be Used Inside the<head> Tag?

The <head> element in an HTML document contains metadata, scripts, and links that are not rendered on the page but provide important information about the document.

Here are some common tags that can be used inside the <head> tag:

  • <title>: Defines the web page's title, displayed in the browser's title bar or tab.
  • <meta>: Provides metadata about the web page, such as character encoding, viewport settings, description, keywords, and more.
  • <link>: Used to link external resources like CSS stylesheets, favicons, and other related files.
  • <style>: Allows embedding internal CSS styles for the web page.
  • <script>: Includes external JavaScript files or embed inline JavaScript code.
  • <base>: Specifies the base URL for relative URLs within the document.
  • <noscript>: Defines alternative content to display if the browser lacks support or has JavaScript disabled.
  • <template>: Represents a reusable template for HTML content.

16. What Is an HTML Layout?

The HTML layout refers to how a website's content is arranged and structured, making it easy to navigate.

There are several HTML layout elements, including:

  • Header: The <header> tag in front-end development is used to designate the top portion of a web page, known as the header section.
  • Navigation bar: The navigation bar, or the menu list, displays content information through hyperlinks. The <nav> tag is specifically used to integrate this navigation section into web pages.
  • Index / Sidebar: This section holds extra information or advertisements and isn't always required to be included on the page.
  • Content section: In web design, the <main> tag specifies the central part of the page where content is displayed.
  • Footer: The footer section is positioned at the bottom of web pages and typically includes contact information and related queries. This section is defined using the <footer> tag.

17. What Are Semantic Elements?

Semantic elements in HTML are named to describe content in a way that is both human-readable and machine-readable.

Elements like <main>, <header>, <footer>, and <section> are examples of semantic elements because they precisely describe the primary purpose and type of content contained within these tags.

18. What Are HTML Entities?

HTML entities are special characters or symbols represented by a specific code or sequence, usually starting with an ampersand (&) and ending with a semicolon (;). They display characters that cannot be easily typed or are reserved for specific purposes in HTML.

Some common HTML entities:

  • &lt; represents the less-than symbol (<) used for opening tags.
  • &gt; represents the greater-than symbol (>) used for closing tags.
  • &amp; represents the ampersand symbol (&) used for HTML entities.
  • &quot; represents the double quote symbol (").
  • &apos; represents the single quote symbol (').
  • &nbsp; represents a non-breaking space.
  • &copy; represents the copyright symbol (©).
  • &reg; represents the registered trademark symbol (®).
  • &#65; represents the character code for "A" (use &#code; for any character code).

19. How Can We Add Symbols in HTML?

HTML uses certain characters as part of its syntax, giving them special significance. To display these characters as regular text or symbols without triggering their special functions, we use HTML entities. These entities allow us to safely include reserved characters and symbols in our web pages.

Some common special symbols and their corresponding HTML entities:

  • Copyright Entity: ©
  • Registered Trademark Entity: ®
  • Trademark Entity: ™
  • At Symbol Entity: @
  • Paragraph Mark Entity: ¶
  • Section Symbol Entity: §
  • Double-Struck Capital Entity: 𝕔

20. What Is HTML Encoding?

HTML encoding refers to converting special characters in HTML into their respective character entities. For example, consider the double quotation mark (").

In HTML, double quotes are used to define attribute values in tags. If you want to display a double quotation mark as part of your visible text, you must encode it. The HTML entity for a double quote is &quot;.

HTML encoding is essential for preserving the intended appearance of your content while maintaining valid HTML syntax. It's particularly important when displaying text that includes characters with special HTML meanings, such as direct quotes, code samples, or technical documentation.

21. How to Add CSS Styling in HTML?

There are three main ways to add CSS styling to an HTML document:

  • Inline CSS: You can add CSS styles directly to an HTML element using the style attribute.
  • <h1 style="color: blue; font-size: 24px;">Learning Hub</h1>
  • Internal CSS: You can include CSS styles within the <head> section of an HTML document using the <style> element.
  • <head>
      <style>
        h1 {
          color: blue;
          font-size: 24px;
        }
      </style>
    </head>
  • External CSS: You can create a separate CSS file and link it to your HTML document using the <link> element in the <head> section.
  • <head>
      <link rel="stylesheet" href="styles.css">
    </head>

    In the styles.css file:

    h1 {
      color: blue;
      font-size: 24px;
    }

Using an external CSS file is generally considered the best practice as it separates the HTML from the CSS, making the code more maintainable and reusable across multiple HTML pages.

22. How to Add JavaScript to an HTML Web Page?

There are three main ways to add JavaScript to an HTML web page:

JavaScript inside <head> tag

This method places JavaScript code within <script> tags in the <head> of your HTML document. It's useful for scripts that need to load before the page content.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript in Head</title>
    <script>
        function changeContent() {
            document.getElementById("demo").innerHTML = "Top 90+ HTML Interview Questions and Answers in 2024";
        }
    </script>
</head>
<body>
    <h1>JavaScript in Head Example</h1>
    <p id="demo">Learning Hub</p>
    <button onclick="changeContent()">Change Content</button>
</body>
</html>

JavaScript inside <body> tag

This method places the <script> tags just before the closing </body> tag. It's beneficial for scripts interacting with page elements, ensuring the DOM is fully loaded before the script runs.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript in Body</title>
</head>
<body>
    <h1>JavaScript in Body Example</h1>
    <p id="demo">Learning Hub</p>
    <button id="changeButton">Change Content</button>

    <script>
        document.getElementById("changeButton").addEventListener("click", function() {
            document.getElementById("demo").innerHTML = "Top 90+ HTML Interview Questions and Answers in 2024";
        });
    </script>
</body>
</html>

External JavaScript

This method involves creating a separate .js file and linking it to your HTML document. It's ideal for larger scripts and promotes better organization and reusability.

HTML file (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>External JavaScript</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h1>External JavaScript Example</h1>
    <p id="demo">Learning Hub</p>
    <button id="changeButton">Change Content</button>
</body>
</html>

JavaScript File (script.js):

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("changeButton").addEventListener("click", function() {
        document.getElementById("demo").innerHTML = "Top 90+ HTML Interview Questions and Answers in 2024";
    });
});

23. What Are Forms in HTML?

Forms in HTML are used to collect user input data and send it to a server for processing. They allow users to enter information such as names, email addresses, passwords, comments, and other data types.

The <form> element is used to create a form, and it can contain various form control elements such as:

  • <input>: Used for various input fields like text, email, password, checkbox, radio button, etc.
  • <textarea>: Used for multi-line text input.
  • <select> and <option>: Used for creating dropdown lists.
  • <button>: Used for creating clickable buttons, often used for form submission.

Example of a simple form:

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

  <label for="phone">Phone Number:</label> 
  <input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required>

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

24. What Is the Difference Between Cellpadding and Spacing?

In HTML tables, cellpadding and cell spacing are properties that control the appearance of table cells, but they have different objectives.

ParametersCellpaddingCellspacing
PurposeDefines the space between a table cell's border and its contentDefines the space between adjacent cells
CreationCreated using the HTML <table> tag with cellpadding attributeCreated using the HTML <table> tag with cellspacing attribute
ScopeApplies to a single cellApplies to multiple cells simultaneously
Default Value12
EffectivenessMore effective and widely usedComparatively less effective than cellpadding

25. Define Applets

Applets are small applications or programs written in the Java programming language that can be embedded into a web page. They were designed to run within a web browser and provide interactive and dynamic content to the user.

Applets were primarily used in the early days of the Internet to create interactive graphics, games, and other multimedia applications that could run within a web browser. They were embedded into a web page using the <applet> HTML tag, which specified the location of the Java applet code.

However, due to security concerns and the widespread adoption of alternative technologies like JavaScript, Flash (now obsolete), and HTML5, applets have fallen out of favor. They are no longer widely used in modern web development.

26. How Is the Ruler Attribute Different From Border Attributes?

When the border attribute is set to zero, default cell borders and thickness are applied. However, adding a rule attribute to a tag replaces the border attribute, showing a default one-pixel border instead.

...

27. What Are Some HTML5 APIs, and How Are They Used?

HTML APIs, known as Application Programming Interfaces, include definitions and protocols designed specifically for HTML. Tools associated with HTML APIs are utilized for direct configuration within HTML code.

Here are some common HTML5 APIs and their uses:

  • Canvas API: Allows you to draw graphics, animations, and visualizations directly on a web page using JavaScript. It provides a programmable rendering surface for creating dynamic and interactive content.
  • History API:Allows web applications to manipulate the browser's session history, enabling features like single-page applications and deep linking.
  • Geolocation API: This API enables web applications to retrieve the user's geographic location with the user's permission. It can be used for location-based services, mapping applications, and context-aware features.
  • File API: Allows web applications to interact with the user's local file system, enabling features like file upload, drag-and-drop, and file manipulation.
  • Web workers API: Enables the creation of background threads in JavaScript, allowing for parallel processing and computationally intensive tasks without blocking the main user interface thread.
  • WebSocket API: Facilitates real-time, bidirectional communication between a web client and a server through a persistent connection, enabling features like chat applications, real-time updates, and multiplayer games.
  • Web audio API: Provides a high-level JavaScript API for processing and synthesizing audio, enabling advanced audio manipulation and creating audio visualizations.
  • Fullscreen API: Allows web applications to display content in full-screen mode, providing an immersive experience for multimedia applications, games, and presentations.

28. How Do You Optimize an HTML Page’s Load Time?

Optimize the load time of an HTML page by scaling down image and media sizes, compressing CSS and JavaScript files, merging files to decrease HTTP requests, and using lazy loading for non-urgent scripts and images.

29. How Do You Create a Navigation Bar Using HTML and CSS?

To create a navigation bar using HTML and CSS, follow these steps:

  • HTML structure: Use an unordered list (<ul>) with list items (<li>) for each navigation link.
  • <nav>
      <ul>
        <li><a href="#home">Home</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#services">Services</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
    </nav>
  • CSS styling: Here's a basic CSS to style the navigation bar:
  • nav {
      background-color: #333;
    }
    
    nav ul {
      list-style-type: none;
      padding: 0;
      margin: 0;
      overflow: hidden;
    }
    
    nav li {
      float: left;
    }
    
    nav li a {
      display: block;
      color: white;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
    }
    
    nav li a:hover {
      background-color: #111;
    }

30. What Are the Differences Between <blockquote> and <q> Tags?

The following are the differences between <blockquote> and <q> tags:

Parameters<blockquote><q>
PurposeLong quotations.Short, inline quotations.
DisplayBlock-level element.Inline element.
Default stylingIndented on both sides.Adds quotation marks.
LengthMultiple lines.Usually, within a sentence.
Line breaksPreserves line breaks.Do not add line breaks.
CitationCan use cite attributes.Can use cite attributes.
NestingCan contain other block elements.Cannot contain block elements.

31. How Do You Structure a Multi-page Website Using HTML?

To structure a multi-page website using HTML, create distinct HTML files for each page with consistent naming conventions. Use <a> tags to link these pages and ensure a coherent layout by organizing content semantically with HTML5 elements.

32. What Are the Best Practices for Using Headings in HTML?

When using headings in HTML, it's important to follow best practices to ensure proper structure, accessibility, and semantics.

  • Begin new sections with equal or higher-level headings.
  • Start subsections with lower-level headings.
  • Reserve H1 for the page's main title or topic.
  • Maintain a continuous sequence of heading levels.
  • Avoid skipping levels to prevent user confusion.
  • Outline the document structure before writing.
  • Ensure headings accurately reflect content hierarchy.
  • Use headings to improve both readability and SEO.

33. How Do You Use the <figure> and <figcaption> Elements in HTML?

HTML provides the <figure> and <figcaption> elements for associating images, diagrams, or illustrations with descriptive captions. The <figure> element wraps the content, while the <figcaption> element links the content with its caption.

34. What Is the Difference Between GET and POST Methods in Form Submission?

The method attribute specifies how form data should be submitted to the server in HTML forms. The two most common values for this attribute are GET and POST, representing different data transmission methods.

Here's the difference between the GET and POST methods in form submission:

AspectsGETPOST
Data VisibilityData visible in URL.Data is not visible in the URL.
Data LengthLimited by URL length (typically 2048 characters).No practical length limit.
SecurityLess secure, not for sensitive data.More secure and suitable for sensitive data.
CachingCan be cached.Not typically cached.
BookmarkingCan be bookmarked with parameters.Cannot be bookmarked with full data.
Use CaseRetrieving data and search queries.Submitting data and file uploads.
IdempotencyIdempotent (repeated requests have the same effect).Not idempotent (repeated requests may have different effects).
EncodingURL encoded.Can use various encodings (e.g., multipart/form-data).
PerformanceSlightly faster for small amounts of data.Better for large amounts of data.

35. What Are WebSockets?

WebSockets are a communication protocol that facilitates full-duplex communication channels over a single TCP connection. They enable real-time, event-driven connections between clients and servers.

Unlike traditional HTTP, which operates on a request-response model, WebSockets support bi-directional communication. This allows clients and servers to send data to each other asynchronously, eliminating the need for continuous polling.

WebSockets are commonly used in scenarios where real-time, bidirectional communication is required, such as:

  • Chat applications.
  • Real-time notifications and updates.
  • Collaborative editing tools.
  • Online gaming.
  • Internet of Things (IoT) communication.
  • Live data streaming (e.g., stock tickers, sensor data).

Subscribe to the LambdaTest YouTube Channel and get detailed tutorials around automation testing, Selenium, and more.

HTML Interview Questions for Experienced

Following are the HTML interview questions for experienced professionals covering advanced topics, including HTML5 APIs, accessibility standards, and performance optimization.

1. What Are Void Elements?

Void elements are a special category of HTML elements that only have start tags and do not contain any content within them. Void elements in HTML do not have closing tags and cannot contain any content; they can only include attributes. Adding a slash before the end of the start tag is optional.

Some examples of void elements in HTML include:

  • <br> (line break)
  • <hr> (horizontal rule)
  • <img> (image)
  • <input> (form input)
  • <link> (external resource link)
  • <meta> (metadata)
  • <source> (media source)
  • <wbr> (word break opportunity)

2. How Do You Create a Box Element in HTML?

A box element in HTML can be created by a <div> tag with CSS styling.

Following is the most basic example:

<div style="width: 300px; height: 200px; border: 1px solid black;">
  A rectangular box
</div>

This creates a simple rectangular box with a width of 200 pixels, a height of 100 pixels, and a thin black border.

3. How Are Container Tags Different From Empty Tags in HTML?

Container tags and empty tags are different types of tags used in HTML. Here are the differences between them:

AspectsContainer TagsEmpty Tags
StructureHave opening and closing tags.Single self-closing tag.
ContentCan contain other elements or text.Cannot contain content.
Example<div>...</div>, <p>...</p><br>, <img>
ClosingRequire a separate closing tag.Close within the same tag (e.g., <img />).
PurposeUsed to wrap and structure content.Used for singular elements or actions.
NestingCan be nested within other elements.Cannot be nested.
Common UsesParagraphs, divisions, lists.Line breaks, images, input fields.

4. What Are Logical and Physical Tags in HTML?

HTML uses physical and logical tags to improve users' readability and understanding of text, although these tags have distinct functions, as their names suggest.

  • Logical tags: Logical tags in HTML are utilized to present text in logical styles. Below are some commonly used logical tags:
  • TagsUses
    <header>Defines a header for a document or section
    <nav>Defines navigation links
    <article>Defines independent, self-contained content
    <section>Defines a section in a document
    <side>Defines content aside from the page content
    <footer>Defines a footer for a document or section
    <strong>Indicates strong importance
    <em>Emphasizes text
    <cite>Defines the title of a work
    <time>Defines a date/time
  • Physical tags: Physical tags in HTML apply actual physical formatting to text. Below are some commonly used physical tags:
  • TagsUses
    <b>Bold text
    <i>Italic text
    <u>Underlined text
    <font>Specifies font face, size, and color (deprecated)
    <center>Centers text (deprecated)
    <big>Increases text size (deprecated)
    <small>Decreases text size

5. Explain MathML in HTML 5.

MathML (Mathematics Markup Language) has been part of HTML5 since its third version, launched in 2015, allowing web browsers to display mathematical equations and expressions like other HTML elements. The first version of MathML was initially introduced in 1998, followed by subsequent updates leading to the current version.

MathML provides an accessible means to visually represent complex mathematical formulas and equations. Its integration into HTML5 mandates that all MathML tags be nested within <math> and </math< tags. Designed for machine-to-machine communication, MathML is primarily utilized by specialized authoring tools, including equation editors, and holds relevance across various applications.

Note: It's important to note that MathML is not a calculator or a programming language. It cannot solve equations but rather displays them in a standardized format.

To use MathML in HTML5, the structure of content is like this:

<!DOCTYPE html>
<html>
<head>
    <title>HTML5 MathML Example</title>
</head>
<body>
    <math>
        <!-- MathML content goes here -->
    </math>
</body>
</html>

Some of the most common MathML tags include:

MathML TagsUses
<mrow>Creates a row containing mathematical expressions.
<mi>Represents identifiers (variables, function names).
<mn>Displays numeric characters.
<mo>Shows mathematical operators.
<mfrac>Creates fractions.
<msqrt> and <mroot>Display square roots and nth roots.
<msub> <msub> and <msub>Handle subscripts and superscripts.
<mtable> <mtr> and <mtd>Create tables or matrices.

6. What Do You Mean by Manifest File in HTML5?

A manifest is a text file that directs the browser to cache particular files or web pages, allowing them to remain accessible even offline. The <html> tag in HTML5 includes a manifest attribute to specify which web pages should be cached. When a web page has this attribute or is listed in the manifest file, it will be stored for offline access upon user visits.

Manifest files, which use the .appcache extension, always start with CACHE MANIFEST. These files are divided into three sections: CACHE, NETWORK, and FALLBACK.

  • CACHE: This section lists resources (web pages, CSS, JavaScript, images) cached after the first download, allowing offline use.
  • For example:

    <!DOCTYPE html>
    <html manifest="offline.appcache">
    <body>
        <h1>LambdaTest Learning Hub</h1>
    </body>
    </html>

    This file, when listed in the CACHE section of offline.appcache, will be available offline.

  • NETWORK: Resources listed here are never cached and always require a server connection.
  • For example:

    <!DOCTYPE html>
    <html>
    <body>
        <h1>LambdaTest Learning Hub</h1>
        <p>Only available in online mode!</p>
    </body>
    </html>

    When listed in the NETWORK section, this file will only be accessible online.

  • FALLBACK: This specifies alternative resources to use when a page is inaccessible. It lists primary resources and their fallbacks for offline use.
  • Online version (offline.html):

    <!DOCTYPE html>
    <html>
    <body>
        <h1>LambdaTest Learning Hub</h1>
        <p>Working in online mode</p>
    </body>
    </html>

    Offline fallback (fallback.html):

    <!DOCTYPE html>
    <html>
    <body>
        <h1>LambdaTest Learning Hub</h1>
        <p>You are working in offline mode.</p>
    </body>
    </html>

    A sample manifest file (offline.appcache) might look like this:

    CACHE MANIFEST
    
    CACHE:
    cache.html
    
    NETWORK:
    network.html
    
    FALLBACK:
    offline.html fallback.html

    To implement this, create an index.html file linking all the above files:

    <!DOCTYPE html>
    <html manifest="offline.appcache">
    <body>
        <h1>LambdaTest Learning Hub</h1>
        <a href="cache.html">Cached File</a>
        <a href="network.html">Network File</a>
        <a href="offline.html">Fallback File</a>
    </body>
    </html>

7. How to Open a Hyperlink in Another Window or Tab in HTML?

It's common in web design to open hyperlinks in new windows or tabs to enhance user experience, allowing them to view additional content without navigating away from the current page.

In HTML, this functionality is easily implemented using the target attribute of the anchor (<a>) tag with "_blank" as the value, directing the browser to open the linked document in a new tab or window.

Syntax:

<a href="URL" target="_blank">Link Text</a>

8. Explain Web Workers in HTML.

Web Workers are JavaScript-based multithreaded objects designed to run scripts in the background, ensuring that application or web page performance remains unaffected.

Web Workers allow for the execution of lengthy scripts without interruption from user interaction scripts, ensuring that CPU-intensive operations can be performed without impacting the responsiveness of the web page. They are commonly used for handling substantial computational tasks.

There are two main types of Web Workers:

  • Dedicated Workers:
    • The most common type of Web Worker.
    • Created by a single script and can only communicate with that script.
    • Used for running scripts in the background of a single page.
  • Shared Workers:
    • Can be accessed by multiple scripts running in different windows, iframes, etc.
    • Allows communication between multiple pages of the same origin.
    • Useful for sharing data between multiple tabs or windows.

9. How to Handle JavaScript Events in HTML?

To handle events in HTML, add a function to an HTML tag that executes JavaScript when any associated event is triggered. HTML provides multiple event attributes, including keyboard events, mouse events, and form events, each serving specific roles.

The syntax for handling events in HTML:

<element eventAttribute="myScript">

HTML offers various event attributes, categorized into different types such as keyboard events, mouse events, and form events. Let's explore some common form events:

  • onblur: This event occurs when an object loses focus.
  • <element onblur="myScript">
  • onchange: This event is triggered when the value of an element changes.
  • <element onchange="myScript">
  • onfocus: This event happens when an element receives focus.
  • <element onfocus="myScript">

10. What Is the Difference Between an Event Handler and an Event Listener?

An event handler is a function that triggers automatically in response to an event, while an event listener is an object that receives notifications when the event occurs. The listener can then respond by invoking an event handler.

11. What Is the Role of the onblur() Method?

The onblur() method specifies actions to take when an element loses focus. This frequently validates input fields before users move to the next field.

12. Which Is Better, External Functions or Inline Functions for Event Handlers? Why?

It's generally best practice to avoid using inline functions for event handlers in web development. This is because inline functions can generate anonymous functions that are difficult to debug and may lead to unexpected closures. Instead, external functions are preferred as they are easier to debug and manage.

13. What Happens if an Event Handler Returns False?

When an event handler returns false, it stops the event from progressing further. This behavior is frequently used to prevent actions such as form submissions.

14. What Is the Purpose of the “datetime” Attribute in the “time” Element?

In HTML, the datetime attribute defines the date and time connected with the content, making it machine-readable. It is used with elements like <time> to present structured time-related data.

Syntax:

<element datetime="YYYY-MM-DDThh:mm:ssTZD">

This attribute uses a single value string that encodes date and time information. The components of this string are:

  • YYYY: Four-digit year (e.g., 2024)
  • MM: Two-digit month (e.g., 15 for July)
  • DD: Two-digit day of the month (e.g., 13)
  • T: A mandatory separator between date and time
  • hh: Two-digit hour in 24-hour format (e.g., 15 for 3 PM)
  • mm: Two-digit minutes
  • ss: Two-digit seconds
  • TZD: Time Zone Designator (e.g., Z for UTC, or +/-hh:mm for offsets)

The datetime attribute is particularly useful with these HTML elements:

  • <time>: For marking up specific times or date ranges.
  • <ins>: To indicate when content was inserted into a document.
  • <del>: To show when content was removed from a document.

15. What Is an Anchor Tag in HTML?

The <a> tag in HTML defines a hyperlink, allowing navigation from one page to another. Its primary attribute, href, specifies the destination URL. Clicking the link directs the user to this specified location.

Syntax:

<a href="link">Link Name</a>

Common usage examples:

  • Basic link:
  • <a href="https://www.lambdatest.com/learning-hub/">Visit Learning Hub</a>
  • Opening in a new tab:
  • <a href="https://www.lambdatest.com/learning-hub/" target="_blank">Visit Learning Hub</a>
  • Email and phone links:
  • <a href="mailto:example@xyz.com">Send email</a>
    <a href="tel:+910000000">+910000000</a>
  • Internal page anchors:
  • <a href="#sectionA">Go to Section A</a>

16. What Is an Anchor Tag in HTML?

Server-sent events (SSE) is a standard protocol in HTML5 that allows servers to push data to clients over a persistent connection. This feature enables real-time updates and communication between the server and the client without the client having to poll the server for new data constantly.

With server-sent events, the server can initiate and send data to the client whenever new information becomes available. This makes it suitable for applications that require real-time updates, such as live news feeds, stock tickers, chat applications, or live scoring updates.

17. Explain Input Types Provided by HTML5 for Forms.

HTML5 introduced several input types for forms, allowing for better data validation and user experience. Below are some of the input types:

  • color: Displays a color picker for selecting a color value.
  • date: Allows the user to select a date from a date picker.
  • datetime-local: Allows the user to select a date from a date picker.
  • email: Validates the input as an email address.
  • month: Allows the user to select a month and year.
  • number: Allows the user to enter a numeric value, with options for setting minimum, maximum, and step values.
  • range: Displays a slider control for selecting a numeric value within a range.
  • search: Displays a text input field designed for entering search queries.
  • tel: Allows the user to enter a telephone number.
  • time: Allows the user to select a time value.
  • url: Validates the input as a URL.
  • week: Allows the user to select a week and year.
Note

Note : Test your HTML forms across 3000+ real desktop browsers. Try LambdaTest Now!

18. Explain Geolocation API in HTML5.

HTML geolocation is used to retrieve a user's geographical coordinates, subject to user consent due to privacy considerations. It allows web applications to request and utilize location data, providing a more contextual and tailored experience. This feature finds extensive use in various scenarios, such as:

  • Local business discovery: Helping users find nearby shops, restaurants, or services.
  • Map-based applications: Providing accurate navigation and location plotting.
  • Weather services: Offering localized weather forecasts and alerts.
  • Social media: Enabling location-based check-ins and friend finders.
  • Content personalization: Delivering region-specific news, offers, or content.

The geolocation API leverages JavaScript to communicate location data in latitude and longitude coordinates to the web application's backend server.

Syntax:

var loc = navigator.geolocation;

19. Write HTML5 Code to Demonstrate the Use of Geolocation API.

Here's an example of how to use the geolocation API in HTML5:

<!DOCTYPE html>
<html>
<head>
    <title>Geolocation Example</title>
</head>
<body>
    <h1>Geolocation Distance Tracker</h1>
    <button onclick="startTracking()">Start Tracking</button>
    <button onclick="stopTracking()">Stop Tracking</button>
    <div id="status"></div>
    <div id="distance"></div>

    <script>
        let watchId, startPos;

        function startTracking() {
            if (navigator.geolocation) {
                document.getElementById('status').textContent = 'Tracking started...';
                watchId = navigator.geolocation.watchPosition(updatePosition, handleError);
            } else {
                document.getElementById('status').textContent = 'Geolocation not supported';
            }
        }

        function stopTracking() {
            if (watchId) {
                navigator.geolocation.clearWatch(watchId);
                document.getElementById('status').textContent = 'Tracking stopped';
            }
        }

        function updatePosition(position) {
            if (!startPos) {
                startPos = position.coords;
                return;
            }
            let distance = calculateDistance(startPos, position.coords);
            document.getElementById('distance').textContent = `Distance moved: ${distance.toFixed(2)} meters`;
        }

        function calculateDistance(start, end) {
            const R = 6371e3; // Earth's radius in meters
            const φ1 = start.latitude * Math.PI/180;
            const φ2 = end.latitude * Math.PI/180;
            const Δφ = (end.latitude - start.latitude) * Math.PI/180;
            const Δλ = (end.longitude - start.longitude) * Math.PI/180;

            const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
                      Math.cos(φ1) * Math.cos(φ2) *
                      Math.sin(Δλ/2) * Math.sin(Δλ/2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

            return R * c;
        }

        function handleError(error) {
            document.getElementById('status').textContent = `Error: ${error.message}`;
        }
    </script>
</body>
</html>

The provided code illustrates the use of the HTML5 geolocation API to track a user's movement. It uses the watchPosition() method to continuously monitor location changes. When tracking starts, it records the initial position and then calculates the distance moved from this starting point using the Haversine formula. The script includes functions to start and stop tracking, update the position, calculate distance, and handle errors.

20. Explain Web Components and Their Usage.

Web components are modular pieces of code that package the essential structure of HTML elements, along with CSS and JavaScript, allowing them to be utilized universally across websites and web applications. Web Components consist of four main building blocks:

  • Custom elements: Custom Elements allow developers to create new HTML tags and define their behavior using JavaScript. These elements can be used just like standard HTML elements, making creating reusable and modular components easier.
  • Shadow DOM: The Shadow DOM is a separate DOM tree that encapsulates a component's internal structure and styling. It provides a way to isolate its implementation details from the rest of the web page, helping prevent conflicts with other styles and scripts.
  • HTML templates: HTML templates provide a way to define the structure and content of a component in HTML. A component can be cloned and used multiple times without repeatedly recreating the same markup.
  • HTML imports: HTML Imports (now deprecated) were a way to include and reuse HTML documents in other HTML documents, making sharing and distributing Web Components easier. However, this feature has been replaced by ES6 modules and JavaScript module imports.

Web components offer several benefits, including:

  • Reusability: Components can be easily reused across web applications, promoting code modularity and maintainability.
  • Encapsulation: The Shadow DOM ensures that the component's internal structure and styles are isolated from the rest of the web page, preventing conflicts and improving maintainability.
  • Interoperability: Web components can be used with any JavaScript library or framework, making them a versatile and flexible solution for building web applications.
  • Extensibility: Custom elements can be extended and customized to meet specific requirements, allowing greater flexibility and customization.

21. How to Add Scalable Vector Graphics to Your Web Page?

To add Scalable Vector Graphics to your web page, you can embed the SVG code directly into your HTML document or include it as an external file.

Embedding SVG code directly:

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

In this example, the SVG code is written directly inside the <svg> element, which defines the dimensions and the vector graphics content (in this case, a circle).

Including an external SVG file:

<img src="example.svg" alt="Example SVG">

You can include an external SVG file in your HTML document using the <img> tag, just like a raster image like PNG or JPEG. The browser will render the SVG file as an image.

Other than these HTML interview questions and answers, you can also refer to the HTML Cheat Sheet to get started.

Conclusion

To conclude, developers must be well-prepared for various HTML interview questions during recruitment. Interviews involve multiple stages, and the questions and answers provided in this article are designed to address each of these stages, with a particular focus on the technical interview.

This comprehensive list serves as a valuable resource for both interviewers and candidates. For interviewers, it offers diverse questions to assess a candidate's HTML proficiency across various skill levels. For candidates, it provides an opportunity to review and reinforce their knowledge, ensuring they're ready to demonstrate their expertise.

Note

Download HTML Interview Questions

Note : We have compiled all HTML Interview Question for you in a template format. Feel free to comment on it. Check it out now!!

Frequently asked questions

  • General ...
How to prepare for an HTML interview?
To prepare for an HTML interview, master HTML fundamentals and HTML5 features. Focus on both theoretical knowledge and practical application. Regular coding practice and project work are essential for interview success.
Considering its role in web development, is HTML a language that beginners can easily grasp, or does it require extensive training?
HTML is generally considered very beginner-friendly. Extensive training isn't necessary to start with HTML, but ongoing learning is important to keep up with evolving web standards and best practices. The basics can be learned in a few weeks, but mastery comes with experience and continuous learning.
What are the skills required to become an HTML developer?
To become a proficient HTML developer, you should develop the following skills: HTML fundamentals and HTML5 features, CSS for styling, Basic JavaScript, Responsive design, Web Accessibility, Cross-browser compatibility, Version control (e.g., Git)

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud